Definition of Handler
Primarily accepts data sent by a child thread and updates the UI with this data in conjunction with the main thread
Explain
When the application starts, Android first opens a main thread (that is, the UI thread), and the main thread is the UI control in the admin interface for event distribution. If you need a time-consuming operation at this point, such as: networked read data, you cannot put these operations in the main thread, if you put in the main thread 5 seconds is not completed, you will receive an Android system error prompt "forced shutdown." This time we put the time-consuming operation on a sub-thread, because the child threads involve UI updates, and the Android main thread is not secure, that is, the update UI can only be updated in the main thread. The emergence of handler is to solve this complex problem. Since handler runs in the mainline approached (UI thread), at this time, the handler undertakes to accept the message object passed by the child thread, (contains data), put these messages into the main thread queue, with the main thread to update the UI.
Handler some features
Handler can distribute the Message object and the Runnable object into the main thread, and each handler instance is bound to the one in which it was created
(typically located in the main thread), it has two functions:
- Schedule a message or runnable to execute somewhere in a main thread
- Schedule an action to execute in a different thread
Some ways to distribute messages in handler
- Post (Runnable)
- Postattime (Runnable,long)
- Postdelayed (Runnable Long)
- Sendemptymessage (int)
- SendMessage (Message)
- Sendmessageattime (Message,long)
- Sendmessagedelayed (Message,long)
The Post class method above allows you to arrange a runnable object into the main thread queue,
The SendMessage class method allows you to schedule a message object with data to queue and wait for updates.
Handler instances
publicclassMyHandlerActivityextendsActivity{
Button button;
MyHandler myHandler;
protectedvoid onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.handlertest);
button =(Button) findViewById(R.id.button);
myHandler =newMyHandler();
MyThread m =newMyThread();
newThread(m).start();
}
//接受消息,处理消息 ,此Handler会与当前主线程一块运行
classMyHandlerextendsHandler{
publicMyHandler(){
}
publicMyHandler(Looper L){
super(L);
}
// 子类必须重写此方法,接受数据
@Override
publicvoid handleMessage(Message msg){
super.handleMessage(msg);
// 此处可以更新UI
Bundle b = msg.getData();
String color = b.getString("color");
MyHandlerActivity.this.button.append(color);
}
}
classMyThreadimplementsRunnable{
publicvoid run(){
try{
Thread.sleep(10000);
}catch(InterruptedException e){
e.printStackTrace();
}
Message msg =newMessage();
Bundle b =newBundle();// 存放数据
b.putString("color","我的");
msg.setData(b);
MyHandlerActivity.this.myHandler.sendMessage(msg);// 向Handler发送消息,更新UI
}
}
}
From for notes (Wiz)
Basic usage of Handler