Search code examples
androidmultithreadinghandlerlooper

What causes Looper.Loop() to hang (i.e. never return)


I'm a little confused about something. Basically, I'm spawning a thread, and in addition I want to run a message loop in that thread. I'm basically doing the following: This is straight out of the Android Looper class API documentation. However, my application always gets stuck at Looper.loop() and never returns from it. My current work around for this, is to just create a handler in the main thread (or UI thread) and send messages to that thread instead. However, for the sake of cleanliness and to just make the flow of my application make sense, I'd much rather send my messages to the thread I'm creating.

class LooperThread extends Thread {
      public Handler mHandler;

      public void run() {
          Looper.prepare();

          mHandler = new Handler() {
              public void handleMessage(Message msg) {
                  // process incoming messages here
              }
          };

          Looper.loop();
          // The rest of the code below is a control loop
      }
}

Any thoughts on what might cause Looper.loop() to never return?


Solution

  • Looper.loop creates an infinite loop and only stops when you call quit

    http://developer.android.com/reference/android/os/Looper.html#loop()