开发者

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?


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.


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?


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜