How to implement Runnable with a non-blocking Looper / Handler

When you implement a Runnable that uses Handler and Looper, you get a blocking queue for Message / Runnables in the run () method of your Runnable, because the loop () method blocks.

Like this:

public class Task1 implements Runnable {
    private Handler mHandler;
    private boolean mCancelled = false;

    private void init() {
        Looper.prepare();
        mHandler = new Handler() {
           public void handleMessage(Message msg) {
              // process incoming messages here
           }
        };
        Looper.loop();
    }

    @Override
    public void run() {
        init();

        while (!mCancelled) {
           try {
              // do stuff here
              TimeUnit.SECONDS.sleep(2);
           } catch (InterruptedException e) {
              // handle exception here
              e.printStackTrace();
           }
        }
    }

    public void cancel() {
        mCancelled = true;
        Looper.quit();
    }
}

In the Looper.class implementation , you see that the queue used is making a call to queue.next (), which can be a BLOCK running thread.

public static void loop() {
    // ...
    for (;;) {
        Message msg = queue.next(); // might block
        // ...
    }
}

, . ( ), run(), Bluetooth-. connect() BluetoothSocket, , . ( . BluetoothSocket.connect(). , , , . , , . . /runnable , Looper/Handler.

: Looper/Handler Runnable Looper Runnable, ? Handler, Runnables!

.

: , Looper , BlockingQueue, take() next(), .

+4

All Articles