How to Make Service That Is Unremovable Even If Killed by the System

how to keep my background service active when android system kills my app?

The solution was so simple: Returning START_STICKY from onStartCommand() did the job.

How to make sure a service that runs when the Application is closed does not get killed?

Foreground Service is the only way if you want to assure that the service will not be killed.

The reason for this is that the foreground service always shows a notification to the user and can be killed by the user if he wants to, this is especially important if you want to know for sure what runs on your device.

All previous methods of making permanent running services are deprecated starting from android 9, when a new privacy policy was introduced.

Killing an activity that started a sticky service kills the service too

No, actually. This is a new feature in the Android SDK- killing the app kills all processes connected to the app, and even the app's sticky services will not restart anymore.(EDIT: The service may not restart, depending on the device; apparently sticky services are still a buggy feature on certain versions of android.)

If you want to keep your service perpetually running, you will need to use a ForegroundService, with a persistent notification in the drawer.

Apparently, this is to make sure that no services run without the user's knowledge.

Best way to create a service that doesn't die.(like WhatsApp or Facebook)

Creating a background service that "does not die" is not possible in android.

You can create a service and take certain measures to have it running as much as possible, but the OS will kill it at times and your service will not be running until the OS decides to restart it (in case it is a sticky service).

Things you can do:

  • Make the service sticky, so that it will be restarted by the OS after the OS kills it. It is impossible to predict when it will be restarted. It can be almost instant, it can take seconds, minutes, hours, or more.
  • Start the service when you open the app.
  • Start the service when the app is upgraded, using the MY_PACKAGE_REPLACED broadcast.
  • Start the service when the device is (re)booted, using the BOOT_COMPLETED and REBOOT broadcasts.
  • Override onTaskRemoved in the service, to schedule a restart of the service in case the user swipes away your app from the list of recent apps.
  • Use FCM to periodically send messages to the app with an instruction to start the service in case it is not running anymore.

You can never have a 100% uptime, but this will get you close.



Related Topics



Leave a reply



Submit