2
HandlerThread thread = new HandlerThread("DownloadService");
thread.start();

Is the looper associated with the thread waiting for a message to arrive in the message queue just after thread.start() returns? If so, then all I need to do is to associate the looper of this thread with a class that implements handleMessage(). Would this be the correct implementation?

Narendra Singh
  • 3,990
  • 5
  • 37
  • 78
Amit
  • 519
  • 1
  • 5
  • 20

1 Answers1

1

Is the looper associated with the thread waiting for a message to arrive in the message queue just after thread.start() returns?

Not necessarily. start() only creates a thread that will --at some point in the future-- create a Looper. start() itself does not wait for the looper to be ready.

Edit: However, this usually is not a problem, since HandlerThread.getLooper() will wait for the looper to be properly prepared if it is not yet ready.

Side note: I think HandlerThread is not a well named class, since it actually only creates a Looper.

dhke
  • 15,008
  • 2
  • 39
  • 56
  • no, it **is** a `Thread` (HandlerThread extends Thread), also no need to override `onLooperPrepared` see: http://androidxref.com/4.4_r1/xref/frameworks/base/core/java/android/os/HandlerThread.java#71 – pskink May 18 '15 at 10:31
  • 1
    I'm not complaining about the `Thread`, I'm complaining about the `Handler` since `HandlerThread` does not directly touch `Handler` in any way (`LooperThread` would have been better, maybe). Also: Read the OP's question please. There's a race condition between `start()` returning and attaching a handler in a different thread, because there may not be a `Looper` for the `HandlerThread` yet when you try to attach a handler to it. – dhke May 18 '15 at 10:35
  • 1
    just call: ht.start(); handler = new Handler(ht.getLooper()), that's all – pskink May 18 '15 at 10:37
  • To repeat myself: There's no guarantee that the Looper has already been created when you call `start()`, because the Looper is created asynchronously in the `HandlerThread`. However `getLooper()` waits for the looper to be ready. – dhke May 18 '15 at 10:42
  • 2
    i already did it: see the link i posted, it shows getLooper() source code, so whats wrong in `new Handler(ht.getLooper())` as `getLooper()` is a blocking method? – pskink May 18 '15 at 10:44
  • You are right about `getLooper()`, see edited answer. OP still asks, if the looper is ready directly after `start()` which it isn't. It's ready after `getLooper()`, because `getLooper()` explicitly waits for it. Simply dropping links to source code is not an explanation in my book. – dhke May 18 '15 at 10:48
  • well, there is only one way to get HandlerThread's Looper and it is getLooper() method, so OP needs to call it anyway thus making sure that Looper is ready – pskink May 18 '15 at 10:51