I want a service to run all the time in my application. So I want to restart it even if it is force closed by user. There is definitely a way to do it as apps like facebook are doing it.(Its not done using push notification, facebook restarts its service even if internet is off).
Any help would be appreciated. Thanks!
If I understand correctly, then actually this is not possible, Android feature to force close application was designed to allow user to get rid of unwanted applications, so it disallows any activities from it until user again starts any of its Activity.
Restart the service even if app is force-stopped and Keep running service in background even after closing the app How?
First of all, it is really very bad pattern to run service forcefully against the user's willingness.
Anyways, you can restart it by using a
BroadcastReceiver
which handles the broadcast sent fromonDestroy()
of your service.StickyService.java
RestartServiceReceiver.java
Declare the components in manifest file:
Start the
StickyService
in a Component (i.e.Application
,Activity
,Fragment
):OR
As per the Android document
On Force stop of app, Android just kill the process ID. No warnings, callbacks are given to service/activities. As per the Android document, When the app is killed there are chances that it calls onPause().
When I tried in my app, even onPause() was not called. I think the only way is use to
FLAG_INCLUDE_STOPPED_PACKAGES
intent flag and send it from another appI think the only foolproof solution here is to have 2 services in separate processes (
android:process="somecustomprocessname"
in manifest, in the service entry) that both listen to broadcasts and restart each other, because currently the UI doesn't let users kill multiple processes in one action. You can then set up a pinger thread in each service that checks if the other service is running every 100 milliseconds or so, and if not, attempts to restart it. But this is starting to look more and more like malware...