android中传感器的学习

关于Sensor有关键的三个类:Sensor,SensorManger,SensorEventListener(是一个监听接口)

 

在Sensor类中可以看到android中定义的所有支持的传感器:

Constants
int TYPE_ACCELEROMETER A constant describing an accelerometer sensor type.                // 加速表传感器
int TYPE_ALL A constant describing all sensor types.                     // 周边温度传感器 api level 14以上支持
int TYPE_AMBIENT_TEMPERATURE A constant describing an ambient temperature sensor type           // 温度传感器
int TYPE_GRAVITY A constant describing a gravity sensor type.                    // 重力传感器,api level 9以上支持
int TYPE_GYROSCOPE A constant describing a gyroscope sensor type                 // 陀螺仪传感器
int TYPE_LIGHT A constant describing an light sensor type.                   // 光线传感器
int TYPE_LINEAR_ACCELERATION A constant describing a linear acceleration sensor type.             // 直线加速度传感器 api level 9以上支持
int TYPE_MAGNETIC_FIELD A constant describing a magnetic field sensor type.               // 地磁传感器
int TYPE_ORIENTATION This constant is deprecated. use SensorManager.getOrientation() instead.     
int TYPE_PRESSURE A constant describing a pressure sensor type                 // 压力传感器
int TYPE_PROXIMITY A constant describing an proximity sensor type.                // 近距传感器(打电话过程中结合光线传感器自动关闭屏幕使用)
int TYPE_RELATIVE_HUMIDITY A constant describing a relative humidity sensor type.                
int TYPE_ROTATION_VECTOR A constant describing a rotation vector sensor type.
int TYPE_TEMPERATURE This constant is deprecated. use Sensor.TYPE_AMBIENT_TEMPERATURE instead.    // 温度传感器

 

得到一个Sensor对象的步骤:

  1.SensorManager sm = (SensorManager) getSystemService(SENSOR_SERVICE);

  2.Sensor sensor = _sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);  // 参数从上表中选择

注册SensorEvent监听器:

  sm.registerListener(this, sensor, SensorManager.SENSOR_DELAY_GAME);  

  第二个参数是灵敏度,系统中定义了几个:

int SENSOR_DELAY_FASTEST get sensor data as fast as possible
int SENSOR_DELAY_GAME rate suitable for games
int SENSOR_DELAY_NORMAL rate (default) suitable for screen orientation changes
int SENSOR_DELAY_UI rate suitable for the user interface

  注意:注册监听器后当程序不再需要监听时要取消监听,因为系统不会自动将其取消,这样对电池损耗很大,所以最好在onPause函数中取消监听。

你可能感兴趣的:(android)