Search code examples
androidhandlerlooper

HandlerThread needs to post to own queue


I have a MyThread extending HandlerThread, and I need to post runnables to its queue within the MyThread class.

The only way I know how to do this is by calling

h = new MyHandler(Looper.myLooper());

and thenh.post(r) to post the Runnable r.

But I'm not sure where to put the new MyHandler() line, because the thread needs to be started before I can get the looper. There is another class that starts MyThread and posts runnables to it, but now I need to do it from within the class too. Any ideas?

Edited:

class MyThread extends HandlerThread {


private MyHandler h;
private Runnable r;

MyThread(String name, int priority) {
    super(name, priority);
    //h = new MyHandler();
    r = new MyRunnable();
}

@Override
public void start() {
    super.start();
    //h = new MyHandler();
}

class MyRunnable implements Runnable {
    @Override
    public void run() {
        //...
    }
}

void startCount(long delay) {
    h.postDelayed(r, delay);
}

}

Both commented lines produce the same result: r gets executed in the main thread, instead of being executed in this HandlerThread which is what I want to achieve.


Solution

  • HandlerThread ht = ...
    ht.start();
    Handler h = new Handler(ht.getLooper(), callback)