Reputation: 391
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?
Upvotes: 0
Views: 3036
Reputation: 11
One solution among others:
key words for tutorials :
Hope it helps
Upvotes: 1
Reputation: 3133
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.
Upvotes: 1
Reputation: 13477
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?
Upvotes: 1