简体   繁体   English

等待所有线程在服务中完成

[英]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.

相关问题 我的AsyncTask类中还包含其他线程。 在执行以下方法之前,我如何等待它及其所有线程完成? - My AsyncTask class has other threads in it. How can i wait for it and all of its threads to finish before executing a following method? 等待所有异步方法完成 - Wait for all async methods finish 如何等待所有异步完成? - How to wait for all the async to finish? 完成所有线程后如何关闭ProgressDialog? - How to dismiss ProgressDialog after finish all threads? 如何在 android 中等待多个线程完成而不阻塞 ui? - How to wait for multiple threads to finish without blocking ui in android? Firebase / Android-等待所有线程完成以进行响应 - Firebase / Android - Wait for all thread finish for response 在pararell中执行协程并等待所有完成 - Execute coroutines in pararell and wait for all to finish 如何使代码等待所有请求完成 Android okhttp - How to make the code wait for all of the requests to finish Android okhttp RxJava,Retrofit,Android - 等到所有请求完成 - RxJava, Retrofit, Android - wait untill all requests finish 如何在调用doOnComplete之前等待完成doOnNext中的所有任务? - How to wait to finish all the task in doOnNext before calling the doOnComplete?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM