Android handler messaging mechanism

Source: Internet
Author: User

In the previous article, "Android asynctask async task," we described how to use Asynctask to handle network traffic and UI updates asynchronously. In this article, you will use the handler messaging mechanism to handle network traffic and UI updates asynchronously.

Google has referenced the Windows Messaging mechanism to implement a similar messaging mechanism in Android systems. To learn about Android's messaging mechanism, there are several concepts (classes) that must be understood:
1. Message
Messages, which are understood as data units for inter-thread communication. For example, a background thread that needs to update the UI after processing the data can send a message containing the update information to the UI thread.
2. Message Queue
Message Queuing, used to store messages published through Handler, followed by FIFO execution.
3, Handler
Handler is the primary processor for message, which is responsible for adding messages to message queues and processing messages in message queues.
4, Looper
The circulator, acting as a bridge between the message queue and the handler, loops out the message within the message queue and delivers it to the corresponding handler for processing.
5. Thread
The UI thread is usually the main thread, and the Android launcher will create a message Queue for it.
Each thread can contain a Looper object and a MessageQueue data structure.

Operating mechanism:
Each thread can and can have only one looper instance, Message Queuing MessageQueue is created in Looper's constructor and is saved as a member variable, that is, MessageQueue is unique relative to the thread. The Android app will create a Looper instance for the main thread by default on startup, and the MessageQueue within the relevant handler and looper to activities, Services, broadcase Management of receivers and so on. In a child thread, Looper needs to call Looper explicitly. The prepare () method is created. The prepare () method guarantees the uniqueness of the Looper within the thread through threadlocal, if Looper online range has been created and attempts to recreate "only one Looper can be created per thread" exception will be thrown.

Handler can specify looper at the time of creation, so messages sent through Handler's SendMessage () method will be added to Looper inside the specified MessageQueue. Without specifying Looper, handler binds the looper of the thread that created it. If the Looper of this thread does not exist, the program will throw "Can ' t create handler inside thread that have not called looper.prepare ()".

The general flow of the entire message processing is:
1. Wrapping the Message object (specifying handler, callback function, carrying data, etc.);
2. Send the message out by a similar method, such as Handler's SendMessage ();
3. Add the message to the MessageQueue of the handler bound Looper in the handler processing method;
4. The loop () method of Looper is used to process the message from the MessageQueue and remove the finished message;
5. Complete the processing of the message by invoking the Handlermessage () method of the handler object bound by the message.

The following still illustrates the use of the handler using the data interface for the aggregated data air quality City Air PM2.5 index.
Example: Handlerdemo
Operating effect:


Code Listing:
Layout file: Activity_main.xml
<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "android:layout_width=" match_parent "android:layout_height=" Match_parent "Android:orien tation= "Vertical" tools:context= ". Mainactivity "> <linearlayout android:layout_width=" match_parent "android:layout_height=" Wrap_cont            Ent "android:orientation=" horizontal "> <textview android:layout_width=" wrap_content "            android:layout_height= "Wrap_content" android:layout_weight= "1" android:gravity= "center"            android:text= "City:" android:textsize= "23sp"/> <edittext android:id= "@+id/city" Android:layout_width= "Wrap_content" android:layout_height= "Wrap_content" Android:layout_we        ight= "3" android:inputtype= "text"/> </LinearLayout> <button android:id= "@+id/query" AndroidOid:layout_width= "Match_parent" android:layout_height= "wrap_content" android:text= "Query" Android:text Size= "23sp"/> <textview android:id= "@+id/result" android:layout_width= "Match_parent" an droid:layout_height= "Match_parent"/></linearlayout>

Java source code file: Mainactivity.java
Package Com.rainsong.handlerdemo;import Java.io.ioexception;import Java.net.urlencoder;import java.util.ArrayList; Import Org.apache.http.httpresponse;import Org.apache.http.namevaluepair;import org.apache.http.client.HttpClient ; Import Org.apache.http.client.methods.httpget;import Org.apache.http.impl.client.defaulthttpclient;import Org.apache.http.message.basicnamevaluepair;import Org.apache.http.util.entityutils;import android.app.Activity; Import Android.os.bundle;import android.os.handler;import Android.os.message;import Android.view.menu;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.button;import Android.widget.edittext;import Android.widget.textview;import Android.widget.toast;public class MainActivity Extends Activity {private static final String juhe_url_environment_air_pm = "http:    WEB.JUHE.CN:8080/ENVIRONMENT/AIR/PM ";    private static final String Juhe_appkey = "The APPKEY value you applied for"; private static final int msg_success = 0;    private static final int msg_failure = 1;    EditText et_city;    Button Btn_query;    TextView Tv_result;    String City; Private Handler Mhandler = new Handler () {@Override public void Handlemessage (Message msg) {SWI                TCH (msg.what) {case MSG_SUCCESS:tv_result.setText ((String) msg.obj);            Break Case MSG_FAILURE:Toast.makeText (mainactivity.this, "Query failed", Toast.length                _long). Show ();                Tv_result.settext ("");            Break    }        }    };        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        Et_city = (EditText) Findviewbyid (r.id.city);        Tv_result = (TextView) Findviewbyid (R.id.result);        Btn_query = (Button) Findviewbyid (r.id.query); Btn_query.setonclicklistener (New OnclicklisTener () {public void OnClick (view view) {city = Et_city.gettext (). toString (); if (City.length () < 1) {Toast.maketext (mainactivity.this, "Please enter city name", Toas                    T.length_long). Show ();                    Tv_result.settext ("");                Return } new Thread () {public void run () {arraylist&lt ;                        namevaluepair> headerlist = new arraylist<namevaluepair> (); Headerlist.add (New Basicnamevaluepair ("Content-type", "text/html;                        Charset=utf-8 "));                        String targeturl = juhe_url_environment_air_pm;                        arraylist<namevaluepair> paramlist = new arraylist<namevaluepair> ();                        Paramlist.add (New Basicnamevaluepair ("key", Juhe_appkey));                Paramlist.add (New Basicnamevaluepair ("Dtype", "JSON"));        Paramlist.add (New Basicnamevaluepair ("City");                            for (int i = 0; i < paramlist.size (); i++) {Namevaluepair Nowpair = Paramlist.get (i);                            String value = Nowpair.getvalue ();                            try {value = Urlencoder.encode (value, "UTF-8");                                } catch (Exception e) {} if (i = = 0) {                            TargetUrl + = ("?" + nowpair.getname () + "=" + value);                            } else {TargetUrl + = ("&" + nowpair.getname () + "=" + value);                        }} httpget HttpRequest = new HttpGet (targeturl); try {for (int i = 0; i < headerlist.size (); i++) {Httpreq Uest.addheader (Headerlist.get (i).GetName (), Headerlist.get (i). GetValue ());                            } HttpClient HttpClient = new Defaulthttpclient ();                            HttpResponse HttpResponse = Httpclient.execute (HttpRequest); if (Httpresponse.getstatusline (). Getstatuscode () = = () {String strresult = entityutils.t                                Ostring (Httpresponse.getentity ());                                Mhandler.obtainmessage (Msg_success, strresult). Sendtotarget ();                            Return                                } else {mhandler.obtainmessage (msg_failure). Sendtotarget ();                            Return                        }} catch (IOException e) {e.printstacktrace ();            }}}.start ();    }        }); } @OverRide public boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu, this adds items to the action bar if I        T is present.        Getmenuinflater (). Inflate (R.menu.main, menu);    return true; }}

API Knowledge Points
public class
Handler
Extends Object

Android.os.Handler

Class Overview
A Handler allows you to send and process Message and Runnable objects associated with a thread ' s MessageQueue. Each Handler instance are associated with a single thread and that thread ' s message queue. When you create a new Handler, it's bound to the thread/message queue of the thread that's creating it--from that PO int on, it'll deliver messages and runnables to that message queue and execute them as they come out of the message Queu E.

Public constructors
Handler ()
Default Constructor Associates This handler with the Looper for the current thread.

void Handlemessage(Message msg)
Subclasses must implement this to receive messages.

Final Message Obtainmessage ()
Returns a new message from the global message pool.

Final Message Obtainmessage(int what, Object obj)
Same as Obtainmessage (), except that it also sets the WHO and OBJ members of the returned Message.

Public final class
Message
Extends Object
Implements Parcelable

Android.os.Message

Class Overview
Defines a message containing a description and arbitrary data object that can is sent to a Handler. The This object contains the extra int fields and an extra object field, that is, to the not does allocations in many cases.

void Sendtotarget()

Sends this Message to the Handler specified by Gettarget ().



Android handler messaging mechanism

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.