一、传感器概念
1:传感器(Sensor)是什么?
传感器是能标识温度,加速度等等物理现象的转换电子信号的机器。Android SDK,在移动设备中提供了各种各样的传感器的API
2:Sensor类
public final Class Sensor extends Object
java.lang.Object
android.hardware.Sensor
Class Overview
See Also
主要的方法
| 方法 | 处理内容 |
public float getMaximumRange() | 返回传感器的最大值 |
public String getName() | 返回传感器的名字 |
public float getPower() | f返回传感器的功率(mA毫安) |
public float getResolution() | 返回传感器的精度 |
public int getType() | 返回传感器的类型 |
public String getVentor() | 返回Vendor名 |
public int getVersion() | 返回传感器的版本号 |
3:传感器有几种类型:
方向传感器: Sensor.TYPE_ORIENTATION
加速度(重力)传感器: Sensor.TYPE_ACCELEROMETER
光线传感器: Sensor.TYPE_LIGHT
磁场传感器: Sensor.TYPE_MAGNETIC_FIELD
距离(临近性)传感器: Sensor.TYPE_PROXIMITY
温度传感器: Sensor.TYPE_TEMPERATURE
在摇动手机的功能中,我们只用加速度传感器就OK了
加速度传感器返回值的单位是加速度的单位 m/s^2(米每二次方秒),有三个方向的值分别是
values[0]: x-axis 方向加速度
values[1]: y-axis 方向加速度
values[2]: z-axis 方向加速度
其中x,y,z方向的定义是以水平放置在的手机的右下脚为参照系坐标原点
x 方向就是手机的水平方向,右为正
y 方向就是手机的水平垂直方向,前为正
y 方向就是手机的空间垂直方向,天空的方向为正,地球的方向为负
所以说,你的手机放置的空间位置不同,它三个方向的加速度也不同。在这里,三个方向的加速度,与我们传统意义上的加速度(9.8m/s2)有所区别,需细细品味以上是摇动手机后清除TextView的文字的代码
参考:http://www.eoeandroid.com/thread-211798-1-1.html
二、注意
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 not disable sensors automatically when the screen turns off.
大家可以看到,文档里要求我们不需要的传感器尽量要解除注册,特别是我们的activity处于失去焦点的状态时。如果我们不按照以上去做的话,手机电池很快会被用完。
还要注意的是当屏幕关闭的时候,传感器也不会自动的解除注册。
所以我们可以利用activity 中的 onPause() 方法和onresume()方法。在onresume方法i中对传感器注册监听器,在onPause()
方法中解除注册。
参考:http://blog.sina.com.cn/s/blog_6f3ff2c90100sryp.html
转载于:https://www.cnblogs.com/cc-Cheng/archive/2013/03/14/2959521.html