Search code examples
androidfreezebackground-serviceandroid-recents

android background service stopping when running more other apps


I am currently trying to make an android app that never ends(restarting when freeze/stopped/swiped/killed etc..) for a certain use.

So I am using background service with onTaskRemoved() to restart service when swiped out of recent app list. Also START_STICKY to keep it running background.

My app responds to my voice well(it shows toast) when there are not many new apps running on top of it. But when some time flies or there are 3~4 running apps on top of it, it just freezes(Does not respond to my voice).

Is there a way to make my app either always be running on top of other apps(like always on top of recent app list that shows up when pressed home button few seconds) or just simply restart the app if frozen?

Please help me out. I know it may sound weird trying to create an app that never ends, but if you help me out it will be a great help for my project.

Thank you :)


Solution

  • For android do not stop the service you can call startForeground()

    However, some services will be missed by the user if they mysteriously vanish. For example, the default music player application that ships with Android uses a service for the actual music playback. That way, the user can listen to music while continuing to use their phone for other purposes. The service only stops when the user goes in and presses the stop button in the music player activity. If that service were to be shut down unexpectedly, the user might wonder what is wrong.

    Services like this can declare themselves as being part of the "foreground". This will cause their priority to rise and make them less likely to be bumped out of memory. The trade-off is that the service has to maintain a Notification, so the user knows that this service is claiming part of the foreground. And, ideally, that Notification provides an easy path back to some activity where the user can stop the service.

    To do this, in onCreate() of your service (or wherever else in the service's life it would make sense), call startForeground(). This takes a Notification and a locally-unique integer, just like the notify() method on NotificationManager. It causes the Notification to appear and moves the service into foreground priority. Later on, you can call stopForeground() to return to normal priority.