The use of Android Handlerthread and its Demo-leo Chin-Blog Park
Today we are going to learn the next simple class in Android HandlerThread , although it's a little cumbersome to initialize.
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 . Instantiated in thread 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.
-
Create a handlerthread , which creates a thread that contains looper.
handlerthread handlerthread = new Handlerthread ("leochin.com");
Get HandlerThread the Looper
Looper Looper = Handlerthread.getlooper ();
Create handler, initialize by Looper
Handler Handler = new Handler (looper);
We successfully created 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.
The use of Android Handlerthread and its demo