1

My application has a service which needs to stay alive even after the user closes it (by swiping it away). My service prints log messages every second in a parallel thread.

Although it does return START_STICKY, it gets terminated as soon as the application is closed by the user. Here is my onStartCommand method:

public int onStartCommand(Intent intent, int flags, int startId) {

    super.onStartCommand(intent, flags, startId);
    instance = this;
    Log.i("Service", "started");
    new Thread(() -> {
        int i = 0;
        while (true) {
            Log.i("Service", "#" + ++i);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }).start();

    start_recording(null);


    return START_STICKY;
}

I've also declared it in the manifest:

<service
    android:name=".MyService"
    android:stopWithTask="false"
/>

How can I prevent the system from killing the thread upon application exit? No other SO post has provided me with a solution which works.

Victor2748
  • 4,149
  • 13
  • 52
  • 89

1 Answers1

1

Based on the documentation:

When an app goes into the background, it has a window of several minutes in which it is still allowed to create and use services. At the end of that window, the app is considered to be idle. At this time, the system stops the app's background services, just as if the app had called the services' Service.stopSelf() methods.

Starting from Android O OS enforces several restrictions on how freely the background services can be executed. X minutes after app's exit, the services will be terminated as if stopSelf() was called. You need to use ForegroundService if you still want to continue but you need to consider impact on battery life. If you perform CPU intensive work, then usage of ForegroundService won't help.

You can refer to my answer in this SO for further details.

Sagar
  • 23,903
  • 4
  • 62
  • 62
  • Thank you. I just have a problem: ForegroundService is not a class I can extend. How can I create a foreground service? – Victor2748 May 02 '18 at 02:20
  • You need to extend it as normal Service. The way it is called is changed. Instead of calling `startService()` you will call `startForegroundService()` check out this [SO](https://stackoverflow.com/questions/6397754/android-implementing-startforeground-for-a-service) – Sagar May 02 '18 at 02:22