Handler mechanism vest Android's Taotao

First need to understand a basic concept ANR: Application not response application that is not responding, that is, the saying goes crash.

The reason Anr are:

The main thread needs to do a lot of important things, respond to click events, updating the UI
if blocked for too long in the main thread which time the application is not responding.

In order to avoid the application appears anr, all the time-consuming operations should be placed in the sub-thread execution. Operate as access to the network can only be performed inside the child thread


The solution:
the main thread execution ----> contains an object Handler, the message queue to place the message queue, Looper view the message queue is kept
in a message to be processed whether, if there is handed handler in the handleMessage method for processing the request.
Child thread ---> Get a resource to change the main UI thread ---> Send a request to the main thread.
Then: Handler has a class called in the main thread, message processor for processing the request to change the sub-thread sends the UI.
Summary:
1. The use of sub-thread sends a message handler request, which is placed in the message queue of the main thread. // message queue is a FIFO queue.
2. There is a looper message polling in the main thread, the equivalent of a patrol, stop to see whether the message queue in the message to be processed request
3. If the looper found a new message, it calls the method handlemessage to process the message. Note that only the main thread can modify the view object.

handler process flowchart is as follows:

// coding steps:
1. Create message processor main thread
2. The thread sends a message to the sub-main thread
3. When the method is called looper handlemessage obtained after process messages.
Handler Handler Handler = new new Private ();
public void the handleMessage (the Message MSG) {
IF (msg.what == 123) {
Bitmap Bitmap = (Bitmap) msg.obj;
iv.setImageBitmap (Bitmap); // IV based interface the ImageView.
}


}
// This is the child thread to the main thread sends a message
the Message the Message MSG = new new ();
msg.what = 123;
msg.obj = Bitmap;
handler.sendMessage (MSG);

// Note: the contents of the display are also within the Toast update UI operation, it is also required handler process.

Guess you like

Origin www.cnblogs.com/Jeely/p/10949314.html