Android Bind Service to the Application cross Activities

The Problem

Sometimes we want to bind an Android Service in our activities and wrap inside e.g. our communication to our backend. Now the problem arrises then we unbind it again. As usually if we change activities we want this service to survive and be in the very next activity. As soon we close the last activity we usually want to have this service destroyed.

Just call bindService in onResume and unbindService in onPause would lead to a restart of the service on each activity change. If we move the calls into onStart and onStop then the Service will just live as long as our application lives.  Even if it is hidden (e.g. home button press.)Bin

Our Simple Service for this example

Of course don’t forget the XML Service tag in the AndroidManifest.xml.

Solution 1

A straight forward solution would be to register such Activities in an Android Application class, which is basically a singleton and let it handle the life cycle.

Now we can just create a abstract service activity and call onResume and onPause the useService and detach methods. So far we can still run into odd cases in which the service gets destroyed. Far more concerning is that we have all our Activities registered with our Application class, which could lead to memory leaks.

Solution 2

What if we just delay the unbind method in our abstract base activity? An again cancel this delayed unbind?

Again not a lot of less code. But this solution comes with some advantages:

  • We have no single instance where we register all activities
  • We can keep the service open / running for a while, if the user just leaves our app for a short period of time

Paul Sterl has written 20 articles

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">