Background service being paused / killed



I’m implementing an app that listens and takes actions when the user shakes the phone.

So I implemented the following service:

public class ShakeMonitorService extends Service {

    ...
    ShakeDetector shakeDetector;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        shakeDetector= new ShakeDetector(this);
        shakeDetector.start();
        ....
        startForeground(MY_ID, myNotification);
        return Service.START_STICKY;
    }

    ...
}

and start the service in the MainActivity’s onCreate

ContextCompat.startForegroundService(this, 
          new Intent(this, ShakeMonitorService.class));

In the shakeDetector I listen the sensor events for the accelerometer as described here.

It works correctly on my devices but some users reports that it works until they lock their devices for long time (i.e. 3hours). From this moment the app stops detecting the shake gestures even when using the device (screen on) until they launch the app again.

What is going on? I supposed Android kills or suspends the app and stops the service until it is opened again.

How can I avoid this?

Important note: I don’t want to avoid the system to enter in sleep mode, but I want to recover the execution when the system exits the sleep mode.

Answer

i understood that you already started the service as foreground with notification and this will give your service the highest priority. you can easily check if the service is still running or not by checking the notification because the notification will be shown as soon as the service is running. but if the notification is still showing but you notice that the service execution rating is less than you expect(paused and then will run again like round robin). then i think this behavior is caused by the android as an operating system it needs to save the battery as much as possible so the execution of the service will be different when the device is plugged in charger or device is unlocked and on or the device is locked.

but if the notification is becoming dismissed then this mean that the service is killed by some bugs in your code which lead to an exception in your service code or by memory leak and if you already set the service flag to START_STICKY or START_REDELIVER_INTENT the system is starting the service again after a while



Source: stackoverflow