[Android] Getting started with Android messaging mechanism

Source: Internet
Author: User

In the previous section, the access network is first put into a sub-thread to execute,new thread () {}.start (),new thread directly using the anonymous inner class to implement, overriding Run () method, the inner class accesses the external variable, and the variable should be defined as Final the.

Direct operation will be error, only theoriginal thread, created can touch xxxxx, only the main thread can access the View object, is because of synchronization and mutual exclusion of threads

The internal implementation of the update interface to do a check, check whether the update operation is executed in the Ui Thread, if there is no problem, if not throw a run-time exception, Calledfromwrongthreadexception

In the previous section, after we accessed the network in a child thread, we directly called the ImageView object's setimagebitmap () to modify the UI interface. So it 's an error.

We need to, in the sub-thread to tell the main thread a message, we want to modify the interface, the content Bitmap to the main thread, let him help us modify.

A child thread sends a message through Handle, and the message is placed inside the message queue.

The main thread has a Looper message in the polling device

If a new message is found by the poll, call the Handle object's handlemessage () to process the message

Handler is a message handler that must be new out of the main thread

Define Handlerin the member properties of the main thread, directly new Handler anonymous internally rewrite his handlemessage () Method

Inside the child thread, callHandlerobject thatsendMessage (msg)method, put the message into the message queue, parameters:msgis aMessageobjects,NewoutMessageobject, settingMessageobject that WhatProperties=a customintconstants, settingMessageobject thatobjProperties=the content to be passed.

Within the overriding method of the main thread handlermessage , the Message object is obtained, the what property is judged, the call ImageView object that Setimagebitmap () method, put Message object that obj attribute is put in.

 PackageCom.tsh.internetpic;ImportJava.io.InputStream;Importjava.net.HttpURLConnection;ImportJava.net.URL;Importandroid.app.Activity;ImportAndroid.graphics.Bitmap;Importandroid.graphics.BitmapFactory;ImportAndroid.os.Bundle;ImportAndroid.os.Handler;ImportAndroid.os.Message;Importandroid.text.TextUtils;ImportAndroid.view.View;ImportAndroid.widget.EditText;ImportAndroid.widget.ImageView;ImportAndroid.widget.Toast; Public classMainactivityextendsActivity {protected Static Final intCHANGE_UI = 0; protected Static Final intERROR = 1; PrivateEditText Et_path; PrivateImageView Iv_pic; //The main thread inside defines the message processor     PublicHandler Handler =NewHandler () {@Override Public voidhandlemessage (Message msg) {if(msg.what==change_ui) {                //Change UIBitmap bm=(Bitmap) msg.obj;            Iv_pic.setimagebitmap (BM); }Else if(msg.what==ERROR) {String showmsg=(String) msg.obj; Toast.maketext (mainactivity. This, ShowMsg, 0). Show ();    }        }    }; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); Et_path=(EditText) Findviewbyid (R.id.et_path); Iv_pic=(ImageView) Findviewbyid (r.id.iv_pic); }    //Click     Public voidgetinternetimg (View v) {FinalString Path =Et_path.gettext (). toString (). Trim (); if(Textutils.isempty (path)) {Toast.maketext ( This, "Picture path cannot be empty", 0). Show (); } Else {            //Open a sub-thread            NewThread () {@Override Public voidrun () {Try{URL URL=NewURL (path); HttpURLConnection Conn=(httpurlconnection) URL. OpenConnection (); Conn.setrequestmethod ("GET"); Conn.setconnecttimeout (5000); Conn.setrequestproperty ("User-agent", "" "); intCode =Conn.getresponsecode (); if(Code = = 200) {InputStream is=Conn.getinputstream (); Bitmap BP=Bitmapfactory.decodestream (IS); //Send MessageMessage msg =NewMessage (); Msg.what=change_ui; Msg.obj=BP;                                                    Handler.sendmessage (msg); } Else{Message msg=NewMessage (); Msg.what=ERROR; Msg.obj= "Network connection error";                            Handler.sendmessage (msg); //Toast.maketext (This, "network connection timed out", 0). Show ();                        }                    } Catch(Exception e) {e.printstacktrace ();        }}}.start (); }    }}

[Android] Getting started with Android 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.