How to restart Android Service when it is killed f

2019-08-28 16:42发布

问题:

I have an android application that in onCreate method of Main ACtivity starts a Background Service.

This is a lightweight Service and I want to keep it running all the time. So , I return START_STCKY in onStartCommand() method of Service.

When App is launched and the service starts running,in case,if Only Running Service is killed from the Settings ,and then if App is relaunched ,the onCreate method of app is not called and Service is not restarted.

If I start my Service in onResume() method of Activity , it does not seem to be a good practice to keep on checking if my Service is running or not.

How to handle this situation? I want that when the service is killed and app is relaunched , even though the app was running in background, the service should be restarted.

回答1:

Instead of using startService ,I am using BindService , I bind the Service in onCreate of the application and unbind it in onTerminate of application.

This keeps running my service all the time till the app is running and User is not given any option in App Manager to kill Running Services in my App.