Android Service keep alive

2019-02-22 06:11发布

问题:

I have a small chat application. When it starts it binds to a service. This service has a tcp/ip connection with the server.

When the application is not in foreground my service creates a status notification. So far so good.

When the application is destroyed for example using task manager on "onDestroy" method I call unbind. Now the service is killed. So my question is how I make a service to stay alive even there is no clients bind with it.

Googe doc: " The service will remain running as long as the connection is established (whether or not the client retains a reference on the service's IBinder)."

Thanl you.

回答1:

You can make your service a foreground service, which will display an icon in the notification bar so that the user can see your service is running. Otherwise, you cannot keep your service running. By the way, you should be aware that an everlasting service is an Android antipattern, the system should be able to kill off your app when memory is low, and apps haven't used it in a while. If you are doing something that legitimately needs to live "forever" you should do so with a foreground service.



回答2:

read this:

http://developer.android.com/guide/components/services.html#Foreground



回答3:

If you want to keep your service alive even when your binder activity is destroyed, you can start your service in Activity first then call bindService:

startService(serviceIntent);

bindService(serviceIntent, connection, Context.BIND_AUTO_CREATE);