Multiple timers using same service

2019-06-11 11:25发布

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.

1条回答
Fickle 薄情
2楼-- · 2019-06-11 12:31

Without seeing your code: a call to the method startService will either start the service if it isn't running or call onStartCommand if the service is already started. When a timer starts you could call startService and increment a value(for example a int value representing the live timers). When a timer needs to stop/finishes you could implement a BroadcastReceiver in the Service(like in the link you've shown) to listen for a "close" broadcast coming from other components(you could use this pattern to let the Service know that a new timer has started(a "start" broadcast)).

In that BroadcastReceiver from the Service you would decrement the live timers count and see if you are at 0, if this is the case then stop the Service.

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.

查看更多
登录 后发表回答