Getting started with the Android messaging mechanism

Source: Internet
Author: User
Tags response code

Then deal with the problems that appear in the Android Network picture Viewer

To modify the original program using the Add child thread:

 PackageCom.wuyudong.imagesviewer;ImportJava.io.InputStream;Importjava.net.HttpURLConnection;Importjava.net.MalformedURLException;ImportJava.net.URL;Importorg.apache.http.HttpConnection;ImportAndroid.os.Bundle;Importandroid.app.Activity;ImportAndroid.graphics.Bitmap;Importandroid.graphics.BitmapFactory;Importandroid.text.TextUtils;ImportAndroid.view.Menu;ImportAndroid.view.View;ImportAndroid.widget.EditText;ImportAndroid.widget.ImageView;ImportAndroid.widget.Toast; Public classMainactivityextendsActivity {PrivateEditText Et_path; PrivateImageView IV; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); Et_path=(EditText) Findviewbyid (R.id.et_path); IV=(ImageView) Findviewbyid (R.ID.IV); }     Public voidClick (View view) {FinalString Path =Et_path.gettext (). toString (). Trim (); if(Textutils.isempty (path)) {Toast.maketext ( This, "Picture path cannot be empty", 0). Show (); } Else {             New  Thread () {@Override   public void  run () { //Connect server GET request get picture                    Try{URL URL=NewURL (path); //request to send HTTP from URLHttpURLConnection conn =(httpurlconnection) URL. OpenConnection (); //How to set the requestConn.setrequestmethod ("GET"); Conn.setconnecttimeout (5000); Conn.setreadtimeout (5000); Conn.setrequestproperty ("User-agent",                                "mozilla/5.0 (Windows NT 6.1; WOW64) applewebkit/537.36 (khtml, like Gecko) chrome/45.0.2454.101 safari/537.36 "); intCode =Conn.getresponsecode (); if(Code = = 200) {InputStream is=Conn.getinputstream (); Bitmap Bitmap=Bitmapfactory.decodestream (IS);                        Iv.setimagebitmap (bitmap); } Else{toast.maketext (mainactivity). This, "Show Picture Failed", 0). Show (); }                    } Catch(Exception e) {//TODO auto-generated Catch blockE.printstacktrace (); Toast.maketext (mainactivity. This, "Access failed to get picture", 0). Show ();        }}}.start (); }    }}

Error after running the project:

06-27 19:27:59.613:w/system.err (2471): Android.view.viewrootimpl$calledfromwrongthreadexception:only the original Thread that created a view hierarchy can touch it views.

Who created the View object, who can move the view.

Code: Iv.setimagebitmap (bitmap), the goal is to modify the UI

It is the main thread that can be modified. To control multi-threaded changes to the view synchronization problem set

The modified code is as follows:

 PackageCom.wuyudong.imagesviewer;ImportJava.io.InputStream;Importjava.net.HttpURLConnection;Importjava.net.MalformedURLException;ImportJava.net.URL;Importorg.apache.http.HttpConnection;ImportAndroid.os.Bundle;ImportAndroid.os.Handler;ImportAndroid.os.Message;Importandroid.app.Activity;ImportAndroid.graphics.Bitmap;Importandroid.graphics.BitmapFactory;Importandroid.text.TextUtils;ImportAndroid.view.Menu;ImportAndroid.view.View;ImportAndroid.widget.EditText;ImportAndroid.widget.ImageView;ImportAndroid.widget.Toast; Public classMainactivityextendsActivity {protected Static Final intCHANGE_UI = 1; protected Static Final intERROR = 2; PrivateEditText Et_path; PrivateImageView IV; //1, the main thread to create the message processor Private Handler Handler = new  Handler () {   public void  Handleme Ssage (Android.os.Message msg) {  if (msg.what = = change_ui) {Bitmap Bitmap 
     = (Bitmap) msg.obj;            Iv.setimagebitmap (bitmap); }  Else if (msg.what = = ERROR) {toast.maketext (mainactivity. This, "Access failed to get Picture", 0      ). Show ();    }        };    }; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); Et_path=(EditText) Findviewbyid (R.id.et_path); IV=(ImageView) Findviewbyid (R.ID.IV); }     Public voidClick (View view) {FinalString Path =Et_path.gettext (). toString (). Trim (); if(Textutils.isempty (path)) {Toast.maketext ( This, "Picture path cannot be empty", 0). Show (); } Else {            NewThread () {@Override Public voidrun () {//Connect server GET request get picture                    Try{URL URL=NewURL (path); //request to send HTTP from URLHttpURLConnection conn =(httpurlconnection) URL. OpenConnection (); //How to set the requestConn.setrequestmethod ("GET"); Conn.setconnecttimeout (5000); Conn.setreadtimeout (5000); Conn.setrequestproperty ("User-agent",                                "mozilla/5.0 (Windows NT 6.1; WOW64) applewebkit/537.36 (khtml, like Gecko) chrome/45.0.2454.101 safari/537.36 "); //get the response code returned by the server                        intCode =Conn.getresponsecode (); if(Code = = 200) {InputStream is=Conn.getinputstream (); Bitmap Bitmap=Bitmapfactory.decodestream (IS); //Iv.setimagebitmap (bitmap); //TODO: Tell the main thread a message: Help me change the interface, content: Bitmap                       message msg = new  message ();                            Msg.what = change_ui; Msg.obj = bitmap;                        Handler.sendmessage (msg); } Else {                            //Toast.maketext (Mainactivity.this, "show Picture Failed", 0)//. Show ();                        message msg = new  message (); Msg.what = ERROR;                        Handler.sendmessage (msg); }                    } Catch(Exception e) {//TODO auto-generated Catch blockE.printstacktrace (); //Toast.maketext (mainactivity.this, "Access failed to get Picture",//0). Show ();                     message msg = new  message (); Msg.what = ERROR;                    Handler.sendmessage (msg);        }}}.start (); }    }}

Getting started with the Android messaging mechanism

Related Article

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.