Why creating HandlerThread for one purpose : to pass it's Looper to a new Handler

570 Views Asked by At

I see a lot examples in code were we see the next thing:

HandlerThread thread = new HandlerThread("Thread1");
        thread.start();
        mLoadHandler = new Handler(thread.getLooper())


   mLoadHandler.post(new Runnable() {
            public void run() {
                // run some code
                //methodA();
            }
        });

you can find it also in:

https://github.com/android/platform_packages_apps_browser/blob/master/src/com/android/browser/OpenDownloadReceiver.java

https://github.com/CyanogenMod/android_packages_apps_Gallery3D/blob/8621799408a58f6b9da3492382ce929b3c93c7de/src/com/cooliris/picasa/PicasaService.java

Why they create a HandlerThread for only one purpose: to pass it's Looper to a new Handler. Why don't just extend the HandlerThread and do the all code (methodA()) there? OR create a Handler instance and call there to:

 Looper.prepare();
 Looper.loop();
2

There are 2 best solutions below

2
On

If you want to get the Handler which is associated with the ThreadHandler class you create, you must pass the Looper associated with that ThreadHadler, otherwise the Handler will be associated to the current thread in which it was instantiated. The purpose of creating such a HandlerThread is generally when you want to do same type of job multiple times, you can simply use this Handler object to post a message to the new thread.

I think your question is why would you want to create an inner class rather than implement a separate independent class. If you are creating an inner class then you can access directly members of the the containing class. If you implement a separate class, you would need to pass the required variables/view values to the new class.

3
On

With only the code you show, there is not much difference in dealing with HandlerThread either way.

However, if there are lots of different components all trying to post different Runnables to the same thread, you'd rather not cram all their logic into one class. It's easier in this case to pass around a Handler for these different components to share. This is one scenario, but there could be others.