How to stay connected to an Android service between multiple activities?
-
20-09-2019 - |
Question
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.liviu.simpleMusicPlayer.PlaylistActivity$CounterServiceConnection@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?
Solution
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.
OTHER TIPS
You can bind it from a separate thread as long as you install a looper in that thread