Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Proper way to wait for handler object to be created

Tags:

android

Folks,

Here is a simplified code for my background thread:

    public class MyThread extends Thread {
      private Handler _handler;

      public void run() {
         Looper.prepare();
         this._handler = new Handler();
         Looper.loop();
      }

      public void DoSomething() {
         if (!this.isAlive()) {
            this.start();
         }

         this._handler.post(blah);
      }
    }

The problem I have is that the background thread may not have yet created the handler object when post() call is made. Essentially, I need a wait loop for the handler object to be initialized. What is generated accepted method of doing this under Android?

Thank you in advance for your help.

Regards, Peter

like image 445
Peter Avatar asked Oct 06 '11 01:10

Peter


1 Answers

You can set a flag after you initialize the Handler and wait for this flag before calling post.

An easy way to wait for a flag in a concurrent system is with a CountDownLatch. It would start at 1 and decrement after the Handler is initialized. Check out the details here: http://download.oracle.com/javase/1,5,0/docs/api/java/util/concurrent/CountDownLatch.html

like image 85
spatulamania Avatar answered Nov 14 '22 23:11

spatulamania