Use HandlerThread class

        Recently I encountered a problem in the Handler's handleMessage () function, how to deal with time-consuming operation.

        The idea from the beginning was in handleMessage () function to open a worker thread, time-consuming operation before executing the message to itself. This approach may result in too many threads, affect the efficiency or even inaccurate data.

       Make such a mistake because the constructor of the Handler is not deep understanding, is usually the most used non-argument constructor Handler handler = new Handler (); such a handler is constructed and bonding of the UI thread, so handleMessage () function is not time-consuming operation.

        But there are other constructors Handler, for example Handler handler = new Handler (Looper); use the constructor to create the Handler, which runs in the thread, which depends on the parameters Looper thread. If the parameter Looper worker threads running, then the worker thread bound Handler, in its handleMessage () function can be time-consuming operation directly.

        Therefore, the above problems can be through the initialization Handler, Looper incoming worker threads to solve.

        How to get to the worker thread bonding of Looper?

        Android provides HandlerThread class to let us solve this problem.


Fake code:


HThread = new new HandlerThread HandlerThread ( "myThread");     // create a worker thread called myThread, the thread can be any name change

hThread.start ();                      // start the worker thread, you must perform this step

= New new Handler Handler Handler (hThread.getLooper ()) {          // Handler will work with thread-bound

 public void handleMessage(Message msg){

...........................                                                           // This function can be performed directly consuming operations, to solve the problem.

}

};


to sum up:

      Handler is commonly used in the development of the class, but often the more common things more easy to overlook its implementation principle, probably because more work chores, it may be because there are other, less time will be to learn unfamiliar content, or is a recognized source know enough.

      Learning is no shortcut, only step by step to thoroughly understand the known, the unknown go to learn, in order to progress.



Published 11 original articles · won praise 2 · views 10000 +

Guess you like

Origin blog.csdn.net/zhengyin_tmac/article/details/52381577