Android Basics Getting Started tutorial--3.3 handler message passing mechanism analysis
tags (space delimited): Android Basics Getting Started Tutorial
Introduction to this section
In the first two sections we learned about two kinds of event-handling mechanisms in Android, both of which respond to events, and this section explains
Is the information passing handler in the UI component of activity, I believe many friends know that Android is not allowed to manipulate UI outside the UI thread for thread safety, and many times we do interface refresh through handler to notify UI component updates! In addition to using handler to complete the interface update, you can also use Runonuithread () to update, or even more advanced transaction bus, of course, here we only explain handler, what is handler, execution process, related methods, The difference between a child thread and the main thread in using handler!
1. Learning route Map:
Introduction of the 2.Handler class:
3.Handler Execution Flow chart:
Flowchart Analysis:
Related nouns
- UI Thread : is our main thread, the system initializes a Looper object when creating the UI thread, and also creates a MessageQueue associated with it;
- Handler: The function is to send and process information, if you want Handler to work properly, there is a Looper object in the current thread
- Message: Handler received and processed messages object
- MessageQueue: Message Queuing, FIFO management message, which creates a MessageQueue associated with the Looper object when it is initialized;
- Looper: Each thread can only have one Looper, manage MessageQueue, and constantly remove the message from it to the corresponding handler processing!
Simply put:
When our child thread wants to modify the UI component in the activity, we can create a new handler object to send the message to the main thread, and the information we send will wait for the MessageQueue of the main thread and be fetched by Looper in first-in, first-out order. It is then distributed to the corresponding handler according to the What property of the message object to handle!
4.Handler Related methods:
- void handlemessage(Message msg): A method of handling messages, usually used to be overridden!
- Sendemptymessage (int what): Send an empty message
- sendemptymessagedelayed (int what,long delaymillis): Specifies how many milliseconds to delay sending empty information
- SendMessage (Message msg): Send Message now
- sendmessagedelayed (Message msg): Specifies how many milliseconds to delay sending information
- Final Boolean hasmessage(int what): Checks whether Message Queuing contains a message with a value specified by what property
If the argument is (int What,object object): In addition to judging the What property, you also need to determine whether the object property is a message of the specified objects
Example of 5.Handler use: 1) handler written in the main thread
In the main thread, because the system has initialized a Looper object, so we directly create the handler object, you can send and process information!
code Example:
A simple program to switch pictures regularly, through timer timer, modify the content of ImageView display, thus forming the frame animation
Run:
Implementation code:
Main.xml:
<relativelayout xmlns: Android = "http://schemas.android.com/apk/res/android" xmlns:tools =" Http://schemas.android.com/tools " android:id = "@+id/relativelayout1" android:layout_width =" match_parent " android:layout_height =" match_parent " android:gravity =" center " Tools:context =; <ImageViewandroid:id="@+id/imgchange"android:layout_width="Wrap _content "android:layout_height=" Wrap_content "android:layout_alignparentleft= "true" android:layout_alignparenttop="true" /> </relativelayout>
Mainactivity.java:
Public class mainactivity extends Activity { //define the array ID of the toggle picture intImgids[] =New int[]{r.drawable.s_1, R.drawable.s_2,r.drawable.s_3, R.drawable.s_4,r.drawable.s_5,r.drawable.s_6, R.drawable.s_7,r.drawable.s_8};intImgstart =0;FinalHandler MyHandler =NewHandler () {@Override //Override the Handlemessage method to determine if a subsequent operation is performed based on what value in MSG Public void Handlemessage(Message msg) {if(Msg.what = =0x123) {Imgchange.setimageresource (imgids[imgstart++%8]); } } };@Override protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.activity_main);FinalImageView Imgchange = (ImageView) Findviewbyid (R.id.imgchange);//Use a timer to have handler send an empty message every 200 milliseconds NewTimer (). Schedule (NewTimerTask () {@Override Public void Run() {Myhandler.sendemptymessage (0x123); } },0, $); } }
2) handler written in child threads
If handler is written in a sub-thread, we need to create a Looper object ourselves! The process is created as follows:
1) The Looper.prepare () method is called directly to create a Looper object for the current thread, and its constructor creates a matching MessageQueue;
2) Create a handler object and override the Handlemessage () method to handle information from other threads!
3) Call the Looper.loop () method to start the Looper
Examples of Use:
Enter a number that calculates all prime numbers within this range after the toast is output
Implementation code:
Main.xml:
<linearlayout xmlns: Android = "http://schemas.android.com/apk/res/android" android:layout_width =" match_parent " android:layout_height =" match_parent " android:orientation =; <edittext android:id
= "@+id/etnum" android:inputtype = "number" android:layout_width =" match_parent " android:layout_height =" Wrap_content " android:hint =" Please enter the upper limit "/& gt; <buttonandroid:layout_width="Match_parent"android:layout_height= "Wrap_content" Android:onclick="cal"android:text="calculation"/> </linearlayout>
Mainactivity.java:
Public class calprime extends Activity { Static FinalString Upper_num ="Upper"; EditText Etnum; Calthread Calthread;//define a thread class class calthread extends Thread { PublicHandler Mhandler; Public voidRun () {looper.prepare (); Mhandler =NewHandler () {//define methods for handling messages@Override Public voidHandlemessage (Message msg) {if(Msg.what = =0x123) {intUpper = Msg.getdata (). GetInt (Upper_num); List<integer> nums =NewArraylist<integer> ();//Calculate all prime numbers starting from 2, to upperOuter for(inti =2; I <= Upper; i++) {//With I in all numbers starting from 2, to the square root of I for(intj =2; J <= Math.sqrt (i); J + +) {//If divisible, indicates that the number is not prime if(I! =2&& I% J = =0) {ContinueOuter }} nums.add (i); }//Use Toast to show all prime numbers that are countedToast.maketext (Calprime. This, Nums.tostring (), Toast.length_long). Show (); } } }; Looper.loop (); }} @Override Public voidOnCreate (Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.main); Etnum = (EditText) Findviewbyid (r.id.etnum); Calthread =NewCalthread ();//Start new threadCalthread.start (); }//Provide event handler for button's Click event Public voidCal (View source) {//Create messageMessage msg =NewMessage (); Msg.what =0x123; Bundle bundle =NewBundle (); Bundle.putint (Upper_num, Integer.parseint (Etnum.gettext (). toString ())); Msg.setdata (bundle);//Send a message to handler in a new threadCalThread.mHandler.sendMessage (msg); } }
PS: This example comes from "Android Crazy Handout" ~
Summary of this section
This section is a simple analysis of the handler event transmission in Android, to distinguish Chu Handler,message,messagequeue,
The concept of loop, and the difference between the handler written in the main thread and the child threads!
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Android Basics Getting Started tutorial--3.3 handler message passing mechanism analysis