[英]Wait all threads finish in Service
I have a Service
where I run a task inside a Thread. 我有一个
Service
,可以在线程内运行任务。 I call this Service
many times and obviously it creates the corresponding number of Threads. 我多次调用此
Service
,显然它会创建相应数量的线程。
How am I going to know when no one Thread
is running so I can call stopSelf()
? 我怎么知道什么时候没有一个
Thread
在运行,所以我可以调用stopSelf()
?
The easiest thing to do is make your service subclass IntentService . 最简单的方法是使服务成为IntentService子类。 This is a special kind of Service that will perform work in a background thread, and automatically stop the service when there is no more work to perform.
这是一种特殊的服务,它将在后台线程中执行工作,并在没有更多要执行的工作时自动停止该服务。 There is a single thread per Service that you declare in your manifest.
您在清单中声明的每个服务只有一个线程。 All you do is determine what sort of work you want to perform by implementing its onHandleIntent() , which is automatically run in that background thread for each Intent delivered to it.
您要做的就是通过实现其onHandleIntent()来确定要执行的工作类型,该onHandleIntent()将在后台线程中为传递给它的每个Intent自动运行。
You can keep track of the running threads in an array. 您可以跟踪数组中正在运行的线程。 When each thread completes it should remove itself from the array and call a method that checks if there are any running threads.
每个线程完成后,应将其从数组中删除,并调用一个检查是否有正在运行的线程的方法。 That method just checks if the list of running threads is empty, and if so, calls
stopSelf()
. 该方法仅检查正在运行的线程列表是否为空,如果是,则调用
stopSelf()
。
Or use IntentService
if this suits your needs. 或根据需要使用
IntentService
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.