我有一个从 Activity 调用的服务。此服务注册所有传感器并针对它们注册侦听器。
编辑:我删除了 onSensorChange() 中的两行
**sensorManager.unregisterListener(this);
sensorManager = null;**
现在它可以工作了。为什么?
问题是当我一次做一个时,我的应用程序工作正常,但如果我注册多个传感器,我的应用程序就会崩溃。
这是我的服务的 OnCreate 函数:
@Override
public void onCreate() {
super.onCreate();
mContext = getApplicationContext();
Toast.makeText(getApplicationContext(),"Service Created",Toast.LENGTH_SHORT).show();
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
//mAccelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mMagnetometer = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
//mGyro = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
// mLinearAccelertion = sensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION);
//sensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
sensorManager.registerListener(this, mMagnetometer, SensorManager.SENSOR_DELAY_NORMAL);
//sensorManager.registerListener(this, mGyro, SensorManager.SENSOR_DELAY_NORMAL);
//sensorManager.registerListener(this, mLinearAccelertion, SensorManager.SENSOR_DELAY_NORMAL);
}
这是我的 onSensorChanged 函数:
@Override
public void onSensorChanged(SensorEvent event) {
//Toast.makeText(mContext,"Heelooo" , Toast.LENGTH_SHORT).show();
float[] values = event.values;
Sensor mSensor = event.sensor;
boolean res = CalculatePosition.calculateNewPosition(4.5F,5.3F);
if(res){
Toast.makeText(mContext, "Check", Toast.LENGTH_SHORT).show();
}
//CalculatePosition.test(event);
sensorManager.unregisterListener(this);
sensorManager = null;
}
我在 MyActivity onCreate 函数中启动这样的服务:
intent = new Intent(this, CustomSensorService.class);
startService(intent);