Home » Android » How to stay connected to an Android service between multiple activities?

How to stay connected to an Android service between multiple activities?

Posted by: admin June 15, 2020 Leave a comment

Questions:

I have multiple activities and one service. In MainActivity I successfully connect to service (using a class that implements ServiceConnection + bindService() + startService()) but when I try to apply same method in other activity I see in LogCat a error:

01-15 22:29:37.438: ERROR/ActivityThread(12206): android.app.ServiceConnectionLeaked:  
    Activity com.app.liviu.simpleMusicPlayer.PlaylistActivity has leaked ServiceConnection  
    com.app.li[email protected]43713c90  
    that was originally bound here.

Is it possible to connect to a service in an other way: something like to make static my CounterServiceConnection object in MainActivity and use it in the second one?

How to&Answers:

The error message is fairly self-explanatory: you are leaking a ServiceConnection, by which Android means you are calling bindService() but are not calling unbindService(), and the activity that called bindService() was destroyed. Make sure you call unbindService() in onDestroy(), if not sooner.

something like to make static my
CounterServiceConnection object in
MainActivity and use it in the seconde
one?

No.

Answer:

You can bind it from a separate thread as long as you install a looper in that thread