//创建活动,调用SensorEventListener
public class Sensor extends Activity implements SensorEventListener {
private SensorManager sensorManager;//传感器管理器
private Sensor accelerometer;//加速度传感器
private Sensor orientation; //回旋传感器
//初始化活动
@Override
public void onCreate(Bundle senevent) {
super.onCreate(senevent);
requestWindowFeature(Window.FEATURE_NO_TITLE);
//设定传感器管理器
sensorManager=(SensorManager)getSystemService(
Context.SENSOR_SERVICE);
//设定传感器
List list;
list=sensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER);
if (list.size()>0) accelerometer=list.get(0);
list=sensorManager.getSensorList(Sensor.TYPE_ORIENTATION);
if (list.size()>0) orientation=list.get(0);
}
//程序的开始
@Override
protected void onResume() {
super.onResume();
//传感器信息处理的设定
if (accelerometer!=null) {
sensorManager.registerListener(this,
accelerometer,SensorManager.SENSOR_DELAY_FASTEST);
}
if (orientation!=null) {
sensorManager.registerListener(this,
orientation,SensorManager.SENSOR_DELAY_FASTEST);
}
}
//程序的停止
@Override
protected void onStop() {
//传感器处理的停止
sensorManager.unregisterListener(this);
//程序的停止
super.onStop();
}
//传感器信息的处理
public void onSensorChanged(SensorEvent event) {
//数据的取得
for (int i=0;i<3;i++) {
int w=(int)(10*event.values[i]);
event.values[i]=(float)(w/10.0f);
}
//加速度的取得
if (event.sensor==accelerometer) {
sensorView.setAcceleration(event.values);
}
//方向的取得
if (event.sensor==orientation) {
sensorView.setOrientation(event.values);
}
sensorView.invalidate();
}
//精度变更函数,一般不必修改
public void onAccuracyChanged(Sensor sensor,int accuracy) {
}
}