Handler class:
1 sending a message in a child thread
2 getting and handling message in the main thread
Notifies the UI thread to change the interface in a new thread through the handler mechanism.
Each thread can have only one looper, and each Looper associates a MessageQueue
In the UI thread, the system initializes a Looper object by default.
The functions of Looper, MessageQueue and handler are as follows:
1 Looper: Each thread has only one Looper, it is responsible for managing MessageQueue; Looper.loop () The method will continuously remove the message from the Mssagequeue and distribute the message to the corresponding handler by Msg.target.dispatchMessage (msg);
2 MessageQueue: Managed by Looper, it manages the message by first coming out of the queue.
3 Handler: It can send a message to MessageQueue and is responsible for handling the corresponding message Looper distributed to him.
The message is sent to MessageQueue through the handler object, and MessageQueue is created by Looper.
So the use of handler in the thread is 3 steps:
1 Looper.prepare ()
2 Rewrite handler handlemessage (Message msg) to create handler subclass object
3 Looper.loop ()
How do I create a Looper object in a new thread?
Private class Calthread extends Thread {
Public Handler Handler;
public void Run () {
Looper.prepare ();
Handler = new Handler () {
@Override
public void Handlemessage (Message msg) {
Handler receive, Process message
}
}
Looper.loop ();
}
}
Mcalthread = new Calthread (). Start ();
Message msg = new Message ();
Msg.what = 0x123;
Bundle data = new bundle ();
Data.putint (Extra_data, 11111);
Msg.setdata (data);
The mainline Cheng thread sends a message, receives and processes a message in a child thread (time-consuming operations are processed in a child thread)
MCalThread.handler.sendMessage (msg);
A child thread sends a message to the main thread, receives and processes a message in the main thread (typically used to modify the UI)
The UI thread is primarily responsible for handling user keystroke events, user touch-screen events, and screen drawing events.
Several actions for updating the UI in a new thread:
1 using handler to implement communication between threads
2 Activity.runonuithread (runable)
3 View.post (runable)
4 view.postdelayed (runable, long)
The Asynctask is designed to simplify operations of 2, 3, and 4, and is suitable for simple asynchronous processing.
Asynctask<params, Progress, result>
Precautions for using Asynctask:
1 An instance of Asynctask must be created in the UI thread
2 the Execute () of Aysnctask must be called in the UI thread
3 Asysnctask Various callback methods can not be called manually, only by the system call
4 Each asynctask can only be executed once.
Use of handler and Intentservice