简体   繁体   English

在 android 中让 UI 线程等到服务完成

[英]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:一种解决方案:

  • create a Handler in your UI activity in order to propertly read&write variables (for example create it in the onCreate function)在您的 UI 活动中创建一个处理程序,以便正确地读取和写入变量(例如在 onCreate 函数中创建它)
  • put a BroadCast Receiver in the UI activity在 UI 活动中放置一个广播接收器
  • when your service terminates, send a broadcast message当您的服务终止时,发送一条广播消息
  • your UI activity will receive the message with the broadcast receiver您的 UI 活动将使用广播接收器接收消息
  • Post your instructions to the handler将您的指示发布给处理程序

key words for tutorials:教程关键词:

  • BroadCast Receiver广播接收器
  • sendBroadcast(intent)发送广播(意图)
  • Handler post runnable处理程序发布可运行

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM