I want to collect accelerometer data with my app. Therefore I created a service, so the app collects the data in the background, even when the app is no longer open.
Problem is, that when I close the app, the service gets terminated as well and restarts. During that time it won't collect data.
I tried both START_REDELIVER_INTENT
and START_STICKY
, both with the same result: when the app closes, the service restarts.
Is there way to prevent the service completely from stopping when the app is terminated?
Note that my service is running in a separate process.
Here is my code:
@Override
public void onCreate() {
// start thread
HandlerThread thread = new HandlerThread("SensorData", Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
looper = thread.getLooper();
handler = new BGHndlr(looper);
sensorMngr = (SensorManager) getSystemService(SENSOR_SERVICE);
reader = new SensorReader(sensorMngr);
accSensor = reader.getSingleSensorOfType(Sensor.TYPE_ACCELEROMETER);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Message message = handler.obtainMessage();
message.arg1 = startId;
handler.sendMessage(message);
return START_REDELIVER_INTENT;
}
Nested class:
public class BGHndlr extends Handler implements SensorEventListener {
public BGHndlr(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
oSensorManager.registerListener(this, oAcceleroMeter, SensorManager.SENSOR_DELAY_FASTEST);
}
//int i = 0;
@Override
public void onSensorChanged(SensorEvent event) {
// do something
}
@Override
public void onAccuracyChanged(Sensor sensor, int i) {}
}
both with the same result: when the app closes, the service restarts.
This is a normal Android
behavior, there is nothing an Android
application developer can do about it.
Note that my service is running in a separate process.
Same as before (all in your question proves it)... That said, the answer to
Is there way to prevent the service completely from stopping when the app is terminated?
is No. You, as others, should stick to the Android
components' lifecycle.