简体   繁体   中英

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?

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)
  • put a BroadCast Receiver in the UI activity
  • when your service terminates, send a broadcast message
  • your UI activity will receive the message with the broadcast receiver
  • 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:

To summarize, it's vital to the responsiveness of your application's UI to keep the UI thread unblocked.

That was from the Android Developer page on Painless Threading which you should read in full. 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.

You can use a Semaphore to block the UI thread while the service is executing. There are many ways to do this, but for sake of simplicity, this Semaphore could be a static field in a utility class.

public class UtilityClass {
   public static final Semaphore LOCK = new Semaphore(0);
}

In your UI Thread you would do something like: UtilityClass.LOCK.acquire()

In your service, when done you would release the lock: 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. For example, before releasing a permit you might want to check that there are zero availablePermits()

I think that answers you question, but please be warned that blocking on the UI thread will cause the app to become unresponsive. In other words, this approach is not best practice and should be avoided.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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