How it is possible Service run indefinitely and also allow binding in android?

Khushbu Shah picture Khushbu Shah · Sep 3, 2011 · Viewed 19.5k times · Source

I want a service which can run in the background until I stop, even if the component that started it is destroyed and also allows binding to the activities. How it is possible ?

As per android bound services document - there are three ways of creating bound service

  1. Extending Binder class.
  2. Using Messenger.
  3. Using AIDL.

I have created a bound service using messenger (2nd method). Activity is bind to service in its onStart() method and unbind in its onStop() method. Two way messaging (between activity and service) works properly. But problem is that when activity unbinds service, service is destroyed. But I want a service which can run indefinitely.

It is possible as android Services Dev Guide - "Although this documentation generally discusses these two types of services separately, your service can work both ways—it can be started (to run indefinitely) and also allow binding. It's simply a matter of whether you implement a couple callback methods: onStartCommand() to allow components to start it and onBind() to allow binding."

I also implement onStartCommand() method in service and return START_STICKY, but it is never called. Looking at the lifecycle callbacks of bounded service in dev guide, there is no onStartCommand() callback method. Then how it is possible to run service until we stop and also allow binding?

I am using eclipse platform in fedora 15 OS.

Any Help.....

Answer

Joel F picture Joel F · Sep 7, 2011

You just need to start it with startService() somewhere. This will prevent it from being stopped automatically when there are no more bindings.

From the Service documentation, emphasis mine:

A service can be both started and have connections bound to it. In such a case, the system will keep the service running as long as either it is started or there are one or more connections to it with the Context.BIND_AUTO_CREATE flag.

As others have pointed out, it could still be killed by Android if resources are needed. You can "prioritize" your Service and make it less likely to be killed if you make it a foreground service.