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.