0

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.

sundie
  • 245
  • 3
  • 12
  • I know that calling `new MyHandler(Looper.myLooper()).post(r);` each time I want to post a runnable works fine, but is there a better way to do it? – sundie Jul 16 '13 at 03:23

1 Answers1

0
HandlerThread ht = ...
ht.start();
Handler h = new Handler(ht.getLooper(), callback)
pskink
  • 23,874
  • 6
  • 66
  • 77
  • The thread should have already been started by the time HandlerThread wants to post runnables to its own queue.. My question is, I don't know 'when' to get the handler to its own looper.. it certainly can't be in the constructor because the thread's not started yet there.. – sundie Jul 16 '13 at 06:56
  • the thread was already started by another class.. i don't think you can start the same thread twice? – sundie Jul 16 '13 at 08:01
  • no, you cannot. i think the easiest way is to extend HandlerThread and keep a reference to a Handler here, so when you start this HandlerThread a Handler is. also created and asiigned to a field for later use – pskink Jul 16 '13 at 08:23
  • class MyHandlerThread extends HandlerThread { Handler mHandler; } – pskink Jul 16 '13 at 08:57
  • when is the Handler actually created? – sundie Jul 16 '13 at 09:29
  • try to override start(), call super of course and then create a Handler – pskink Jul 16 '13 at 09:31
  • I tried your suggestion but it still doesn't work! I edited my question to make it clearer – sundie Jul 16 '13 at 09:57
  • instead of //h = new MyHandler(), add h = new MyHandler(getLooper()); – pskink Jul 16 '13 at 10:04
  • it worked!!! thank you so much! but how is getLooper() different from Looper.myLooper()? – sundie Jul 16 '13 at 10:18
  • exactly, see https://github.com/android/platform_frameworks_base/blob/master/core/java/android/os/HandlerThread.java and please click some burtonts to thank me – pskink Jul 16 '13 at 10:29