[英]Making the UI thread to wait untill the service is finished in android
hi all i have a problem i want to make the UI thread to wait untill a service has been finished can any one tell me how to acheive this?大家好,我有一个问题,我想让 UI 线程等到服务完成,谁能告诉我如何实现这个?
One solution among others:一种解决方案:
key words for tutorials:教程关键词:
Hope it helps希望能帮助到你
I can tell you that you should never, never ever be making the UI thread wait:我可以告诉你,你永远不应该让 UI 线程等待:
To summarize, it's vital to the responsiveness of your application's UI to keep the UI thread unblocked.
总而言之,保持 UI 线程畅通对应用程序 UI 的响应能力至关重要。
That was from the Android Developer page on Painless Threading which you should read in full.这来自无痛线程的 Android 开发人员页面,您应该完整阅读。 What are you really trying to do anyway?
你到底想做什么?
I'm going to assume you already have the service setup correctly for communicating with your Activity.我将假设您已经正确设置了与您的 Activity 通信的服务设置。
You can use a Semaphore
to block the UI thread while the service is executing.您可以使用
Semaphore
在服务执行时阻塞 UI 线程。 There are many ways to do this, but for sake of simplicity, this Semaphore
could be a static field in a utility class.有很多方法可以做到这一点,但为了简单起见,这个
Semaphore
可以是实用程序 class 中的 static 字段。
public class UtilityClass {
public static final Semaphore LOCK = new Semaphore(0);
}
In your UI Thread you would do something like: UtilityClass.LOCK.acquire()
在您的 UI 线程中,您可以执行以下操作:
UtilityClass.LOCK.acquire()
In your service, when done you would release the lock: UtilityClass.LOCK.release()
在您的服务中,完成后您将释放锁:
UtilityClass.LOCK.release()
Keep in mind that a few more checks might be necessary to ensure there are no bugs in this approach.请记住,可能需要进行更多检查以确保此方法中没有错误。 You will want to have a look at the
Semaphore
documentation.您将需要查看
Semaphore
文档。 For example, before releasing a permit you might want to check that there are zero availablePermits()
例如,在发布许可证之前,您可能需要检查是否有零个
availablePermits()
I think that answers you question, but please be warned that blocking on the UI thread will cause the app to become unresponsive.我认为这可以回答您的问题,但请注意,阻塞 UI 线程会导致应用程序无响应。 In other words, this approach is not best practice and should be avoided.
换句话说,这种方法不是最佳实践,应该避免。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.