Android main Thread and sub-Thread communication (Thread + handler)
Android is based on Java, so it is also divided into main threads and subthreads!
Main thread: implements business logic, UI rendering and updating, and connects sub-threads, similar to generals;
Sub-thread: completes time-consuming operations (online data retrieval, SD card data loading, and long-running background), similar to Xiao Bing;
I. subthreads send messages to the main Thread (Thread + handler ):
1. Handler defined in the main thread:
Java code
- Handler mHandler = new Handler (){
-
- @ Override
- Public void handleMessage (Message msg ){
- Super. handleMessage (msg );
- Switch (msg. what ){
- Case 0:
- // Do something, refresh UI;
- Break;
- Default:
- Break;
- }
- }
-
- };
2. The subthread sends a message to the main thread after processing the time-consuming operation and updates the UI:
Java code
- MHandler. sendEmptyMessage (0 );
In this way, the message interaction is completed under the condition that the subthread and the main thread have a task division;
2. The main Thread sends messages to the subthread (Thread + handler ):
When the main thread encounters a time-consuming operation, it must be completed by the subthread, and a notification is sent to the subthread. The procedure is as follows:
1. Define Handler in the Child thread. The Handler defines the thread in which it is bound, and the Handler in the thread needs to call logoff. prepare (); method. It is not called in the main thread because the main thread calls it for you by default;
Java code
- Public class LoopThread implements Runnable {
-
- Public Handler mHandler = null;
-
- @ Override
- Public void run (){
- Logoff. prepare ();
- MHandler = new Handler (){
- Public void handleMessage (Message msg ){
- String result = NetUtil. getJsonContent ("Beijing ");
- // Completed the weather retrieval operation in Beijing;
- Log. I ("test", "handler" + result );
- }
- };
- Logoff. loop ();
- }
-
- }
Among them, lorule. prepare (); and lorule. loop (); maintain a message queue, waiting for message injection and execution in the Child thread;
2. This is called in the main thread:
Java code
- LThread. mHandler. sendEmptyMessage (0 );
The main thread sends a message to the subthread so that the subthread executes the specified operation. In Android, another method is HandlerThread. See the following example:
Java code
- HandlerThread handlerThread = new HandlerThread ("jerome ");
- HandlerThread. start ();
-
- /**
- * The logoff created by HandlerThread must be passed to threadHandler to complete the binding;
- */
- ThreadHandler = new Handler (handlerThread. getLooper ()){
-
- @ Override
- Public void handleMessage (Message msg ){
- Super. handleMessage (msg );
- Switch (msg. what ){
- Case 0:
- Time-consuming operations can be performed here;
- Log. I ("jerome", "hello, I am sub thread ");
- Break;
- Default:
- Break;
- }
- }
- };