使用同一服务的多个计时器多个、计时器

2023-09-07 10:23:42 作者:百毒不侵ぬ

我用动作条卡口与多个片段。每个片段包含根据我的计时器服务计时器。当我停止我的第一个计时器(定时器停止服务)第二定时器停止藏汉,我想这是因为他们都运行相同的服务。

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.

是否有可能distiguish如果另一个片段使用该服务或者为每个定时器启动各个服务?或是否有这样做的另一种方式?

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.

推荐答案

在没有看到您的code:调用方法 startService 要么开始,如果该服务它不运行或致电 onStartCommand 如果该服务已经启动。当启动一个定时器,你可以叫 startService 和增量的值(例如 INT 转口货值为presenting的现场定时器)。当定时器需要停止/完成,你可以实现一个广播接收器服务(就像你已经链接所示),以监听关闭播出从其他组件来(你可以使用这个模式来让服务知道,一个新的计时器已经开始(一个开始直播))。

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)).

广播接收器服务你会递减现场定时器计数,看看你在 0 ,如果是这样,那么case停止服务

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.

上述方法的主要问题是什么时候可靠关闭服务即使其它活动被打死,并没有得到重新启动,所以他们不能播出所需的计时器封闭的意图(如果其他活动被打死,不重新启动可能会留下一些注册的定时器服务,你不会希望服务无限期地运行下去)。为了解决这个问题,将需要大约您的实际code更多细节。

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.