Principles of Handler message mechanism (directly explained by code)-Android development and handlerandroid

Source: Internet
Author: User

Principles of Handler message mechanism (directly explained by code)-Android development and handlerandroid

Package com. example. handlertest;

Import android. OS. Bundle;
Import android. OS. Handler;
Import android. OS. logoff;
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;

/**
* Use a demo to describe how Handler Processes
*
*
*
* To introduce the Handler message mechanism, we must first know the difference between "synchronous" and "Asynchronous" communication.
*
* "Synchronous" Communication: for example, if I call James and talk with James, I must wait until the call ends with James before I can call other people.
* (Synchronization means that after a request is sent, nothing will be done, and the following will not be done until the result is returned)
*
* "Asynchronous" Communication: for example, after I send an e-mail to a few students, I do not need to wait for them to reply. I can also do other things, when they reply, the email system will notify me
* (Asynchronous means to notify the caller of the processing result after the request is sent and completed by means of status, notification, or callback)
*
*
* Handler mechanism: after an application is enabled, a UI thread (main thread) is enabled. As its name suggests, it is used to manage UI controls on the interface,
* Distribution of events, such as a Button click event. android distributes the event to the corresponding Button to respond to user operations.
* However, because users may need to perform some time-consuming operations (downloading files), if the android interface does not respond within 5 seconds, a prompt will be displayed.
* The user closes the application. Therefore, these time-consuming operations need to be processed in the subthread. The subthread will update the operation after the subthread completes processing.
* UI in the UI thread, while the Android UI thread is insecure, which means that the UI of the UI thread cannot be directly updated in the Child thread,
* Therefore, Handler is designed in Android to solve this problem!
*
* Solution: Handler runs in the UI thread. It and the sub-thread can transmit data through the Message object. At this time, handler undertakes to receive the Sub-thread.
* The responsibility of the sent Message object is used together with the UI thread to update the UI.
*
*
* Handler message mechanism:
*
*
* 1. How handler accesses messages:
*
* Handler allows sending and processing Message messages. Message messages are sent through the MessageQueue Message Queue associated with the main thread.
* The Runnable object is used for access. When a new handler is created (created in the main thread), the handler belongs to the current main thread.
* MessageQueue is also created synchronously. Handler is bound to the main thread/message queue. In this way, handler can use the message queue of the main thread.
* The Message object is sent and received.
*
*
* 2. Several situations of Handler message processing mechanism [the following code is used to describe these situations]: 2.1 button1: Handler 2.2 button2 in the main thread:
* Handler 2.3 button3 in a child thread: Pass the Handler created by the main thread to another thread to complete message processing. 2.4 button4:
* Update the UI thread interface in other threads. It throws an exception. Let's take a look ~!
*
*
*
* Sending a Message does not block the thread (asynchronous), but receiving a Message will block the thread [when the Handler finishes processing a Message object, it will continue to fetch the next Message for processing] (synchronous)
*
*
* September 11, 2013 23:37:08
*
* @ Author xiaoyaomeng
*
*/

Public class MainActivity extends Activity implements OnClickListener {
HandlerDemo myHandlerDemo = null; // This object is used to create a 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 :{
// Create a Handler instance in the main thread
MyHandlerDemo = new HandlerDemo ();
Message message = myHandlerDemo. obtainMessage (1,
(Object) ("Hello, My name is Handler1 ~~ "));
Message. sendToTarget (); // the Handler sends the message to the UI thread bound to the Handler for processing.
}
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 = new errorHandlerThread (
Button4 );
ErrorHandlerThread. start ();
}
Break;
Default:
Break;
}
}

/*
* MyThread is an internal class and a sub-Thread
*/
Private class MyThread extends Thread {
@ Override
Public void run (){
// TODO Auto-generated method stub
Super. run ();

// 1. error: the Handler object can be created only in the UI thread without the logoff object. Therefore, an exception is reported here.
// MyHandlerDemo = new HandlerDemo ();

// 2. error: The logint obtained by mylogint is null, so an exception is reported.
// MyHandlerDemo = new HandlerDemo (lorule. mylorule ());

// Logoff. getmainlogoff () can be used to obtain the Logoff of the parent class. Therefore, a handler object can be created and bound to MessageQueue.
MyHandlerDemo = new HandlerDemo (logoff. getMainLooper ());
Message message = myHandlerDemo. obtainMessage (2,
(Object) ("Hello, My name is Handler2 ~~ "));
Message. sendToTarget ();

}
}

Private /**
* Create a Handler
*
* @ Author xiaoyaomeng
*
*/
Class HandlerDemo extends Handler {
/* This constructor can be called directly when handler is created in the UI thread */
Public HandlerDemo (){
Super ();
// TODO Auto-generated constructor stub
}

/* This constructor is required to create a Handler in the sub-thread. Otherwise, an error is returned */
Public HandlerDemo (low.logoff ){
Super (logoff );
// 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;

}

}
}
}

/**
*
* Classes of other threads are used to receive a handler and send messages using the handler in the thread.
*
* @ 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 ();

}
}

/**
* The thread that reports an error in the test.
*
* @ 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 ~~~ ");

}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.