0

In the Training documentation on Android, Define a Handler on the UI Thread, see this code

private PhotoManager() { ... /* Instantiates a new anonymous Handler object and defines its handleMessage() method. The Handler *must* run on the UI thread, because it moves photo Bitmaps from the PhotoTask object to the View object. To force the Handler to run on the UI thread, it's defined as part of the PhotoManager constructor. The constructor is invoked when the class is first referenced, and that happens when the View invokes startDownload. Since the View runs on the UI Thread, so does the constructor and the Handler. */ mHandler = new Handler(Looper.getMainLooper()) { ...

An ImageView invokes static method PhotoManager.startDownload(ImageView) passing itself. The image is downloaded on a background thread from a threadpool managed by PhotoManager.

The Handler as instantiated above sets imageView to the downloaded image bitmap.

My question is, as the constructor of PhotoManager ran on UI thread, since PhotoManager class is first referenced from the ImageView (as explained in the comment also), then why is Handler passed an instance of Main (UI thread) Looper. That is, instead of

mHandler = new Handler(Looper.getMainLooper()) {

shouldn't the following would have sufficed?

mHandler = new Handler() {

Or is it just to protect against the case where PhotoManager.startDownload() would have been called from a non-UI thread?

nightlytrails
  • 2,448
  • 3
  • 22
  • 33

1 Answers1

0

Yes you are correct. The Handler() default constructor uses the current thread as its main looper. In the example the Looper is specified as new Handler(Looper.getMainLooper()) which is exactly the same as calling new Handler() if and only if you are executing this code on the main thread.

Quanturium
  • 5,698
  • 2
  • 30
  • 36
  • I know that, but it doesn't exactly answers my question. What about this particular case which I showcased in the question? - Passing Looper.getMainLooper() was not neccessary; isn't? – nightlytrails Feb 13 '15 at 20:45
  • @nightlytrails You haven't added the code triggering the instantiation of the PhotoManager. If you know this code is executed in the main thread, then yes to your question – Quanturium Feb 13 '15 at 21:53