Karthik
Karthik

Reputation: 391

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?

Upvotes: 0

Views: 3036

Answers (3)

user2390881
user2390881

Reputation: 11

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

Upvotes: 1

Tanner Perrien
Tanner Perrien

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

Robert Massaioli
Robert Massaioli

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

Related Questions