I have a service which is called from an Activity. This Service Registers all Sensors and Registers Listener against them.
EDIT: I have removed the two lines in onSensorChange()
**sensorManager.unregisterListener(this);
sensorManager = null;**
AND now it works. WHY?
The Problem is that when I do them one at a time, my application works fine but if I register more than one sensor, My application crashes.
Here is the OnCreate Function of my Service:
@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);
}
Here is my onSensorChanged Function:
@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;
}
I am starting the service like this in MyActivity onCreate Function:
intent = new Intent(this, CustomSensorService.class);
startService(intent);