I use ActionBar tabs with multiple fragments. Each fragment contains a timer based on my timer service. When I stop my first timer (stopping the timer-service) the second timer stops aswell, I guess that's because they are running the same service.
Is it possible to distiguish if another fragment is using the service or maybe to start individual services for each timer? Or is there another way of doing it?
I have been looking for a solution for some time now, I'm a bit lost right now.
Without seeing your code: a call to the method
startService
will either start the service if it isn't running or callonStartCommand
if the service is already started. When a timer starts you could callstartService
and increment a value(for example aint
value representing the live timers). When a timer needs to stop/finishes you could implement aBroadcastReceiver
in theService
(like in the link you've shown) to listen for a "close" broadcast coming from other components(you could use this pattern to let theService
know that a new timer has started(a "start" broadcast)).In that
BroadcastReceiver
from theService
you would decrement the live timers count and see if you are at0
, if this is the case then stop theService
.The main problems with the above approach is when to reliable close the
Service
even if the other activities get killed and are not getting restarted so they can not broadcast the required timer closed intents(if the other activities get killed and are not restarted the service could be left with some registered timers and you wouldn't want the service to run indefinitely). To solve this it would require more details about your actual code.