欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android开发中的重力传感器用法实例详解

程序员文章站 2023-12-05 22:48:10
本文实例讲述了android开发中的重力传感器用法。分享给大家供大家参考,具体如下: 重力传感器与方向传感器的开发步骤类似,只要理清了期中的x,y,z的值之后就可以根据他...

本文实例讲述了android开发中的重力传感器用法。分享给大家供大家参考,具体如下:

重力传感器与方向传感器的开发步骤类似,只要理清了期中的x,y,z的值之后就可以根据他们的变化来进行编程了,首先来看一副图

Android开发中的重力传感器用法实例详解

假设当地的重力加速度值为g
当手机正面朝上的时候,z的值为q,反面朝上的时候,z的值为-g
当手机右侧面朝上的时候,x的值为g,右侧面朝上的时候,x的值为-g
当手机上侧面朝上的时候,y的值为g,右侧面朝上的时候,y的值为-g

了解了重力传感器中x,y,z的含义之后下面我们就开始学习如何使用

首先我们创建一个传感器管理器和一个传感器监听器,管理器用来管理传感器以及创建各种各样的传感器,监听器用来监视传感器的变化并且进行相应的操作

private sensormanager sensormanager;
private mysensoreventlistener mysensoreventlistener;
mysensoreventlistener= new mysensoreventlistener();//这个监听器当然是我们自己定义的,在重力感应器感应到手机位置有变化的时候,我们可以采取相应的操作,这里紧紧是将x,y,z的值打印出来
private final class mysensoreventlistener implements sensoreventlistener{
@override
//可以得到传感器实时测量出来的变化值
public void onsensorchanged(sensorevent event) {
//重力传感器
if(event.sensor.gettype()==sensor.type_accelerometer){
float x = event.values[sensormanager.data_x];
float y = event.values[sensormanager.data_y];
float z = event.values[sensormanager.data_z];
//tv_accelerometer是界面上的一个textview标签,不再赘述
tv_orientation.settext("orientation:"+x+","+y+","+z);
}
}

我们在onresume()方法中创建重力传感器,并向系统注册监听器

protected void onresume() {
 sensor sensor_accelerometer=sensormanager.getdefaultsensor(sensor.type_accelerometer);
 sensormanager.registerlistener(mysensoreventlistener,sensor_accelerometer, sensormanager.sensor_delay_ui);
super.onresume();
}

最后我们在onpause()中注销所有传感器的监听,释放重力感应器资源!

protected void onpause() {
//注销所有传感器的监听
sensormanager.unregisterlistener(mysensoreventlistener);
super.onpause();
}

到此,有关重力传感器的介绍完毕!

接下来看一个android用重力传感器做横竖屏切换的例子

在播放视频的时候,可能要做横竖屏的切换,但是,用户可以设置自己的手机关掉屏幕旋转,这个时候就需要想其他的办法了,比如:重力传感器。

public class screenswitchutils {
 private static final string tag = screenswitchutils.class.getsimplename();
 private volatile static screenswitchutils minstance;
 private activity mactivity;
 // 是否是竖屏
 private boolean isportrait = true;
 private sensormanager sm;
 private orientationsensorlistener listener;
 private sensor sensor;
 private sensormanager sm1;
 private sensor sensor1;
 private orientationsensorlistener1 listener1;
 private handler mhandler = new handler() {
  public void handlemessage(message msg) {
   switch (msg.what) {
   case 888:
    int orientation = msg.arg1;
    if (orientation > 45 && orientation < 135) {
    } else if (orientation > 135 && orientation < 225) {
    } else if (orientation > 225 && orientation < 315) {
     if (isportrait) {
      log.e(test, 切换成横屏);
      mactivity.setrequestedorientation(0);
      isportrait = false;
     }
    } else if ((orientation > 315 && orientation < 360) || (orientation > 0 && orientation < 45)) {
     if (!isportrait) {
      log.e(test,切换成竖屏);
      mactivity.setrequestedorientation(1);
      isportrait = true;
     }
    }
    break;
   default:
    break;
   }
  };
 };
 /** 返回screenswitchutils单例 **/
 public static screenswitchutils init(context context) {
  if (minstance == null) {
   synchronized (screenswitchutils.class) {
    if (minstance == null) {
     minstance = new screenswitchutils(context);
    }
   }
  }
  return minstance;
 }
 private screenswitchutils(context context) {
  log.d(tag, init orientation listener.);
  // 注册重力感应器,监听屏幕旋转
  sm = (sensormanager) context.getsystemservice(context.sensor_service);
  sensor = sm.getdefaultsensor(sensor.type_accelerometer);
  listener = new orientationsensorlistener(mhandler);
  // 根据 旋转之后/点击全屏之后 两者方向一致,激活sm.
  sm1 = (sensormanager) context.getsystemservice(context.sensor_service);
  sensor1 = sm1.getdefaultsensor(sensor.type_accelerometer);
  listener1 = new orientationsensorlistener1();
 }
 /** 开始监听 */
 public void start(activity activity) {
  log.d(tag, start orientation listener.);
  mactivity = activity;
  sm.registerlistener(listener, sensor, sensormanager.sensor_delay_ui);
 }
 /** 停止监听 */
 public void stop() {
  log.d(tag, stop orientation listener.);
  sm.unregisterlistener(listener);
  sm1.unregisterlistener(listener1);
 }
 /**
  * 手动横竖屏切换方向
  */
 public void togglescreen() {
  sm.unregisterlistener(listener);
  sm1.registerlistener(listener1, sensor1,sensormanager.sensor_delay_ui);
  if (isportrait) {
   isportrait = false;
   // 切换成横屏
   mactivity.setrequestedorientation(activityinfo.screen_orientation_landscape);
  } else {
   isportrait = true;
   // 切换成竖屏
   mactivity.setrequestedorientation(activityinfo.screen_orientation_portrait);
  }
 }
 public boolean isportrait(){
  return this.isportrait;
 }
 /**
  * 重力感应监听者
  */
 public class orientationsensorlistener implements sensoreventlistener {
  private static final int _data_x = 0;
  private static final int _data_y = 1;
  private static final int _data_z = 2;
  public static final int orientation_unknown = -1;
  private handler rotatehandler;
  public orientationsensorlistener(handler handler) {
   rotatehandler = handler;
  }
  public void onaccuracychanged(sensor arg0, int arg1) {
  }
  public void onsensorchanged(sensorevent event) {
   float[] values = event.values;
   int orientation = orientation_unknown;
   float x = -values[_data_x];
   float y = -values[_data_y];
   float z = -values[_data_z];
   float magnitude = x * x + y * y;
   // don't trust the angle if the magnitude is small compared to the y
   // value
   if (magnitude * 4 >= z * z) {
    // 屏幕旋转时
    float oneeightyoverpi = 57.29577957855f;
    float angle = (float) math.atan2(-y, x) * oneeightyoverpi;
    orientation = 90 - (int) math.round(angle);
    // normalize to 0 - 359 range
    while (orientation >= 360) {
     orientation -= 360;
    }
    while (orientation < 0) {
     orientation += 360;
    }
   }
   if (rotatehandler != null) {
    rotatehandler.obtainmessage(888, orientation, 0).sendtotarget();
   }
  }
 }
 public class orientationsensorlistener1 implements sensoreventlistener {
  private static final int _data_x = 0;
  private static final int _data_y = 1;
  private static final int _data_z = 2;
  public static final int orientation_unknown = -1;
  public orientationsensorlistener1() {
  }
  public void onaccuracychanged(sensor arg0, int arg1) {
  }
  public void onsensorchanged(sensorevent event) {
   float[] values = event.values;
   int orientation = orientation_unknown;
   float x = -values[_data_x];
   float y = -values[_data_y];
   float z = -values[_data_z];
   float magnitude = x * x + y * y;
   // don't trust the angle if the magnitude is small compared to the y
   // value
   if (magnitude * 4 >= z * z) {
    // 屏幕旋转时
    float oneeightyoverpi = 57.29577957855f;
    float angle = (float) math.atan2(-y, x) * oneeightyoverpi;
    orientation = 90 - (int) math.round(angle);
    // normalize to 0 - 359 range
    while (orientation >= 360) {
     orientation -= 360;
    }
    while (orientation < 0) {
     orientation += 360;
    }
   }
   if (orientation > 225 && orientation < 315) {// 检测到当前实际是横屏
    if (!isportrait) {
     sm.registerlistener(listener, sensor,sensormanager.sensor_delay_ui);
     sm1.unregisterlistener(listener1);
    }
   } else if ((orientation > 315 && orientation < 360) || (orientation > 0 && orientation < 45)) {// 检测到当前实际是竖屏
    if (isportrait) {
     sm.registerlistener(listener, sensor,sensormanager.sensor_delay_ui);
     sm1.unregisterlistener(listener1);
    }
   }
  }
 }
}

使用的时候:

public class mainactivity extends activity implements onclicklistener {
 private screenswitchutils instance;
 @override
 protected void oncreate(bundle savedinstancestate) {
  super.oncreate(savedinstancestate);
  instance = screenswitchutils.init(this.getapplicationcontext());
 }
 @override
 protected void onstart() {
  super.onstart();
  instance.start(this);
 }
 @override
 protected void onstop() {
  super.onstop();
  instance.stop();
 }
 @suppresslint(newapi)
 @override
 public void onconfigurationchanged(configuration newconfig) {
  super.onconfigurationchanged(newconfig);
  log.e(test, onconfigurationchanged);
  if (instance.isportrait()) {
   // 切换成竖屏
   layoutparams params1 = new relativelayout.layoutparams(screenwidth, densityutil.dip2px(this, 160));
   videoview.setlayoutparams(params1);
   toast.maketext(getapplicationcontext(), 竖屏, 0).show();
   log.e(test, 竖屏);
  } else {
   // 切换成横屏
   layoutparams params1 = new relativelayout.layoutparams(screenheight, screenwidth);
   videoview.setlayoutparams(params1);
   toast.maketext(getapplicationcontext(), 横屏, 0).show();
   log.e(test, 横屏);
  }
 }
 @override
 public void onclick(view arg0) {
  switch (arg0.getid()) {
  case r.id.iv_stretch:
   instance.togglescreen();
   break;
  }
 }
}

调用了activity.setrequestedorientation()以后,会触发activity.onconfigurationchanged();可以在这里面重新设置播放界面的大小。

更多关于android相关内容感兴趣的读者可查看本站专题:《android开发入门与进阶教程》、《android视图view技巧总结》、《android编程之activity操作技巧总结》、《android操作sqlite数据库技巧总结》、《android操作json格式数据技巧总结》、《android资源操作技巧汇总》及《android控件用法总结

希望本文所述对大家android程序设计有所帮助。