Transfer from http://www.cnblogs.com/hnrainll/p/3597246.html
Introduced
> First let's see why we're using handlerthread ? In our application to accomplish multiple tasks at the same time, we create multiple threads in the application. In order to allow convenient communication between multiple threads, we will use handler implements communication between threads.
Below we look at how to instantiate handler . Instantiate handler We need to make sure that the thread contains Looper ( Note : ui-thread contains looper by default).
The method for creating looper for threads is as follows: Call Looper.prepare () to initialize Looper in the thread run () method, and then finally call Looper.loop () in the Run () method, so that we can create the looper in that thread. ( note :the Looper.loop () method is a dead loop by default )
Is there a simpler way to implement Looper? Yes, of course.HandlerThread。 Let's see.AndroidRightHandlerThreadDescription of:
Handy class for starting a new thread, which has a looper. The looper can then is used to create handler classes. Note that start () must still is called.
Use steps
Although handlerthread document is relatively simple, but its use is not as easy as it might seem.
-
handlerthread , which creates a thread that contains looper.
handlerthread handlerthread = new Handlerthread ("leochin.com");
-
get handlerthread looper
looper Looper = Handlerthread.getlooper ();
Create handler, initialize by Looper
Handler Handler = new Handler (looper);
We have successfully created the above three steps HandlerThread . The message is sent through handler and is executed in the child thread.
If you want to make handlerthread exit, you need to call handlerthread.quit (); .
Test code
Handlerthreaddemo
Reference:
- Handlerthread
- Android Handlerthread
Written with Leochin.
Use of Android Handlerthread and its demo (RPM)