一、获得SensorManager对象
sensorManager
= (SensorManager) getSystemService(
SENSOR_SERVICE
);
二、获得想得到的传感器(这里获得的是加速传感器)
sensor
=
sensorManager
.getDefaultSensor(Sensor.
TYPE_ACCELEROMETER
);
如果想知道设备上所有的传感器,可以使用
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for(Sensor sensor:sensors)
{
System.out.println(sensor.getName()+"::"+sensor.getVendor()+"::"+sensor.getType());
}
TYPE_ALL代表返回设备所有传感器对象,然后用循环输出传感器的名字等信息,
常用的传感器因手机设备不同而不同,三星S5830上的所有传感器信息如下
![](https://img-my.csdn.net/uploads/201301/04/1357266215_7369.jpg)
三、创建监听器
sensorEventListener
=
new
SensorEventListener() {
public
void
onSensorChanged(SensorEvent event) {
System.
out
.println(
"---"
+event.
values
[0]);
System.
out
.println(
"---"
+event.
values
[1]);
System.
out
.println(
"---"
+event.
values
[2]);
}
public
void
onAccuracyChanged(Sensor sensor,
int
accuracy) {
//
TODO
Auto-generated method stub
}
};
四、为传感器绑定监听器
sensorManager
.registerListener(
sensorEventListener
,
sensor
, SensorManager.
SENSOR_DELAY_NORMAL
);
这样当传感器数据发生变化时就会将事件信息封装成一个event对象传递给监听器,通过监听器中的回调函数实现数据的获取与处理
完整代码如下
package com.android.activity;
import java.util.List;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.app.Activity;
public class SensorActivity extends Activity {
SensorManager sensorManager = null;
Sensor sensor = null;
SensorEventListener sensorEventListener=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
//输出设备上所有传感器信息
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for(Sensor sensor:sensors){
System.out.println(sensor.getName()+"::"+sensor.getVendor()+"::"+sensor.getType());
}
//获取加速度传感器
sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
//声明监听器
sensorEventListener = new SensorEventListener() {
public void onSensorChanged(SensorEvent event) {
System.out.println("---"+event.values[0]);
System.out.println("---"+event.values[1]);
System.out.println("---"+event.values[2]);
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
};
//给传感器绑定监听器
sensorManager.registerListener(sensorEventListener,sensor, SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
protected void onPause() {
//在这里需要将绑定的监听器释放,否则即使程序退出监听程序仍会继续
sensorManager.unregisterListener(sensorEventListener);
super.onPause();
}
}