Package com.example.handlertest;
Import Android.os.Bundle;
Import Android.os.Handler;
Import Android.os.Looper;
Import Android.os.Message;
Import android.app.Activity;
Import Android.view.Menu;
Import Android.view.View;
Import Android.view.View.OnClickListener;
Import Android.widget.Button;
/**
* Through a demo to explain the next several handler processing situation
*
*
*
* In order to introduce the handler message mechanism, we must first know the difference between "synchronous" and "asynchronous" communication
*
* "Synchronous" communication: For example, I call Xiao Ming to talk with Xiao Ming, I have to wait until after the call with Xiao Ming to call someone else's phone
* (synchronization is to send a request, nothing to do, wait until the results are returned before continuing to do the following things)
*
* "Asynchronous" communication: For example, I send e-mail to several students, all sent past, do not need to wait for them to reply here, I can also do other things, they reply, the mailbox system will notify me
* (Asynchronous is the request after the completion of this request, through the status, notification, or callback, etc. to notify the caller to process the results)
*
*
* The cause of the handler mechanism: After an application is opened, a UI thread (the main thread) is first opened, and is used to manage UI controls in the interface, as the name implies.
* and distribution of events, such as a button click event, Android to distribute the event to the corresponding button, in response to user action
* However, because the user may need to do some time-consuming operation (download), but Android if the 5-second interface does not respond, it will prompt
* The user closes the application, so this time it is necessary to put these lengthy operations in the child thread processing, the sub-thread processing is completed before the update
* Interface in UI thread, and Android UI thread is unsafe, which means that the UI thread's interface cannot be updated directly in the child thread.
* So Android has designed handler to solve this problem!
*
* Workaround: Handler runs in the UI thread, and the child thread can pass data through the message object, at which point the handler assumes the receiving child thread
* Comes the responsibility of the Message object, thus updating the UI with the UI thread.
*
*
* Handler message mechanism:
*
*
* 1.handler Access Message principle:
*
* Handler allows you to send and process message messages, message messages through the MessageQueue message queue associated with the main thread, and
* Runnable object for access, when creating a new handler (created in the main thread), handler is the current main thread, the main thread
* MessageQueue is also created synchronously, handler is bound to the main thread/message queue, so that handler can pass through the main thread's message queue
* Send and Receive Message object
*
*
* 2.Handler Message processing mechanism of several situations [below in code to illustrate these situations]: 2.1 Button1: The main thread to do handler 2.2 Button2:
* Sub-thread do handler 2.3 Button3: Pass the handler created by the main thread to other threads to complete the message processing 2.4 Button4:
* Update UI thread interface in other threads, it throws an exception, let's see ha ~!
*
*
*
* Sending a message does not block the thread (async), while receiving message processing blocks the thread [when handler finishes processing a Message object and then takes the next message for processing] (synchronous)
*
*
* September 11, 2013 23:37:08
*
* @author Xiaoyaomeng
*
*/
public class Mainactivity extends Activity implements Onclicklistener {
Handlerdemo Myhandlerdemo = null;//The object is used to create handler in the main thread
Button button1 = null;
Button button2 = null;
Button button3 = null;
Button button4 = null;
@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
Button1 = (Button) Findviewbyid (R.id.button1);
Button2 = (Button) Findviewbyid (R.id.button2);
Button3 = (Button) Findviewbyid (R.id.button3);
Button4 = (Button) Findviewbyid (R.ID.BUTTON4);
Button1.setonclicklistener (this);
Button2.setonclicklistener (this);
Button3.setonclicklistener (this);
Button4.setonclicklistener (this);
}
@Override
public boolean Oncreateoptionsmenu (Menu menu) {
Inflate the menu; This adds items to the action bar if it is present.
Getmenuinflater (). Inflate (R.menu.main, menu);
return true;
}
@Override
public void OnClick (View v) {
TODO auto-generated Method Stub
Handlerdealmessage (V.getid ());
}
private void handlerdealmessage (int id) {
TODO auto-generated Method Stub
Switch (ID) {
Case R.id.button1: {
Creating handler instances in the main thread
Myhandlerdemo = new Handlerdemo ();
Message message = Myhandlerdemo.obtainmessage (1,
(Object) ("Hello,my name is handler1~~");
Message.sendtotarget ()///handler sends a message that corresponds to the UI thread sent to this and the handler binding
}
Break
Case R.id.button2: {
MyThread MyThread = new MyThread ();
Mythread.start ();
}
Break
Case R.id.button3: {
Myhandlerdemo = new Handlerdemo ();
Otherthread otherthread = new Otherthread (Myhandlerdemo);
Otherthread.start ();
}
Break
Case R.ID.BUTTON4: {
Errorhandlerthread errorhandlerthread = new Errorhandlerthread (
BUTTON4);
Errorhandlerthread.start ();
}
Break
Default
Break
}
}
/*
* MyThread is an inner class, child thread
*/
Private class MyThread extends Thread {
@Override
public void Run () {
TODO auto-generated Method Stub
Super.run ();
1.error: Handler objects can only be created in the UI thread without the Looper object, so the exception is reported here
Myhandlerdemo = new Handlerdemo ();
2.error:looper.mylooper gets the Looper is null, so it will also report an exception
Myhandlerdemo = new Handlerdemo (Looper.mylooper ());
The looper of the parent class can be obtained by looper.getmainlooper (), so the handler object can be created successfully and bound MessageQueue
Myhandlerdemo = new Handlerdemo (Looper.getmainlooper ());
Message message = Myhandlerdemo.obtainmessage (2,
(Object) ("Hello,my name is handler2~~");
Message.sendtotarget ();
}
}
private/**
* Create a handler
*
* @author Xiaoyaomeng
*
*/
Class Handlerdemo extends Handler {
/* When creating handler in the UI thread, you can call this constructor directly */
Public Handlerdemo () {
Super ();
TODO auto-generated Constructor stub
}
/* Create a handler in a child thread need to use this constructor, otherwise error */
Public Handlerdemo (Looper Looper) {
Super (Looper);
TODO auto-generated Constructor stub
}
@Override
public void Handlemessage (Message msg) {
TODO auto-generated Method Stub
Super.handlemessage (msg);
Switch (msg.what) {
Case 1: {
Button1.settext (Msg.obj.toString ());
}
Break
Case 2: {
Button2.settext (Msg.obj.toString ());
}
Break
Case 3: {
Button3.settext (Msg.obj.toString ());
}
Break
Default
Break
}
}
}
}
/**
*
* Other thread class, used to receive a handler, and send a message in thread with this handler
*
* @author Xiaoyaomeng
*
*/
Class Otherthread extends Thread {
Private Handler Mhandler;
Public Otherthread (Handler Handler) {
TODO auto-generated Constructor stub
Mhandler = handler;
}
@Override
public void Run () {
TODO auto-generated Method Stub
Super.run ();
Message message = Mhandler.obtainmessage (3,
(Object) ("Hello,my name is handler3~~");
Message.sendtotarget ();
}
}
/**
* Test error errors on the thread
*
* @author Xiaoyaomeng
*
*/
Class Errorhandlerthread extends Thread {
button button = null;
Public errorhandlerthread (Button button) {
TODO auto-generated Constructor stub
This.button = button;
}
@Override
public void Run () {
TODO auto-generated Method Stub
Super.run ();
Button.settext ("hahahaha~~~");
}
}
Some principles of the handler messaging mechanism (direct with code)--ANDROID development