Android之传感器SensorManager

来源:互联网 发布:如何搞垮一个淘宝店铺 编辑:程序博客网 时间:2024/05/16 07:48


SensorManager 

SensorMananger lets you access the device's sensorsGet an instance of this class by  calling  Context.getSystemService()   with the argument SENSOR_SERVICE.

你可以用Context.getSystemService(SENSOR_SERVICE)得到SensorManager,有了它你就可以管理传感器了,其中包含下面提到的方法,getSensorLIst,registerListenerunregisterListener等。

Always make sure to disable sensors you don't need, especially when your activity is paused. Failing to do so can drain the battery in just a few hours. Note that the system will notdisable sensors automatically when the screen turns off.

就是说要记得在不用的时候关掉传感器,因为手机黑屏是不会自动关掉传感器的,当然如果你觉得电量一直都很足,那算我多嘴咯。

官网的例子:

  public class SensorActivity extends Activity, implements SensorEventListener {      private final SensorManager mSensorManager;      private final Sensor mAccelerometer;       public SensorActivity() {          mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);          mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);      }       protected void onResume() {          super.onResume();          mSensorManager.registerListener(this, mAccelerometer,SensorManager.SENSOR_DELAY_NORMAL);      }       protected void onPause() {          super.onPause();          mSensorManager.unregisterListener(this);      }       public void onAccuracyChanged(Sensor sensor, int accuracy) {      }       public void onSensorChanged(SensorEvent event) {      }  } 

 

一般流程:

Sensor编程的一般步骤

1.取得SensorManager

SensorManager sm (SensorManager)getSystemService(SENSOR_SERVICE);

2.实现接口SensorEventListener

public void onAccuracyChanged(Sensor sensor, int accuracy) {}

public void onSensorChanged(SnesorEvent event) {}

3.取得某种Sensor对象

List<Sensor> sensors sm.getSensorList(Sensor.TYPE_TEMPERATURE);

4.注册SensorListener

sm.regesterListener(SensorEventListener listener, Sensor sensor, int rate);

其中第三个参数是延迟时间的精密度。

表格 2感应检测Sensor的延迟时间

参数

延迟时间

SensorManager.SENSOR_DELAY_FASTEST

0ms

SensorManager.SENSOR_DELAY_GAME

20ms

SensorManager.SENSOR_DELAY_UI

60ms

SensorManager.SENSOR_DELAY_NORMAL

200ms

5.取消注册SensorManager

sm.unregisterListener(SensorEventListener listener)






0 0
原创粉丝点击