Android system killed my service when I clear all recent app

android, service

Solution

A long running service needs the following to make it less likely to be terminated:

Return `START_STICKY` from `onStartCommand()`. With this, system will re-start the service even if it has to be stopped for resources limitations.

When the service is not bound to any UI component (e.g an Activity), The service must go in foreground mode by showing a foreground notification. Foreground services are less likely to be terminated by system.

Set the attribute `"stopWithTask"=false` in corresponding `<service>` tag of manifest file.

Also, note that devices from some manufacturers will terminate services even with above properties due to customization:

- Custom task managers.

- Battery saving features that can prohibit non-system services.

Some application services do need to stay in background and have to be aggressively kept alive. Though this method is not recommended, but following steps can be done:

Add triggers for service start : Such as Boot Complete, and Network Connected broadcasts.

If service receives intents/broadcasts `FLAG_RECEIVER_FOREGROUND` in the intent.

An extreme resort is to manually schedule a pending intent for service restart, with `AlarmManager`, when `onTaskRemoved()` is called.

Also, see:

- START_STICKY does not work on Android KitKat

Problem

I already using `startforeground()` at my `Service`, but Android keeps killing my `Service` when I clear all the recent apps. Here's the code of my Service: ``` @Override public int onStartCommand(Intent intent, int flags, int startId) { Notification notification = new NotificationCompat.Builder(this) .setContentTitle("Text") .setTicker("Text") .setContentText("Text") .setSmallIcon(R.drawable.icon) .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.icon)) .build(); startForeground(100, notification); return START_STICKY; } ``` Is there something wrong I did with this code?

Original source

Related problems