Tag:android networkonmainthreadexception Connection network exception
Package com.ccl.getimage;import java.io.inputstream;import java.net.httpurlconnection;import java.net.URL;import android.app.Activity;import android.graphics.Bitmap;import android.graphics.bitmapfactory;import android.os.bundle;import android.text.textutils;import android.view.view;import android.widget.edittext;import android.widget.imageview;import android.widget.toast;public class mainactivity extends activity {private edittext et_path;private imageview iv; @Overrideprotected void oncreate (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 void getimage (View view) {String path = et_path.gettext (). toString (). Trim ( ) if (Textutils.isempty (path)) {Toast.maketexT (this, "address cannot be empty", 0). Show (); return;} Try {url url = new url (path); httpurlconnection conn = (HttpURLConnection) url.openconnection (); Conn.setRequestMethod (" GET "); Conn.setreadtimeout (5000); SYSTEM.OUT.PRINTLN ("Response code is-" +conn.getresponsecode ()), if (Conn.getresponsecode () ==200) {//Gets the stream data returned by the server InputStream in = conn.getinputstream ();//parse the returned stream data into a picture bitmap bitmap = Bitmapfactory.decodestream (in);//Display Picture Iv.setimagebitmap (bitmap); In.close ();} catch (exception e) {e.printstacktrace ();}}
Android Emulator version 4.1.2
Exception Explanation: Network exceptions in the main thread
Cause: The Android2.3 version is not allowed to request network fetch data directly in the main thread
Solution (two types):
One: Add the following code to the OnCreate method (deprecated, possibly blocking the android main thread)
if (Android.os.Build.VERSION.SDK_INT > 9) {strictmode.threadpolicy policy = new StrictMode.ThreadPolicy.Builder (). P Ermitall (). build (); Strictmode.setthreadpolicy (policy);}
Second: Use Android's handler mechanism, and open a sub-thread to request the network to obtain data (recommended use)
Package com.ccl.getimage;import java.io.inputstream;import java.net.httpurlconnection;import java.net.URL;import android.app.Activity;import android.graphics.Bitmap;import android.graphics.bitmapfactory;import android.os.bundle;import android.os.handler;import android.os.message;import android.text.textutils;import android.view.view;import android.widget.edittext;import android.widget.imageview;import android.widget.toast;public class mainactivity extends activity {private edittext et_path;private imageview iv;private string path;//using Handler to update the main thread (UI thread) private handler handler = new handler () {public void handlemessage (message msg) {bitmap bitmap = (Bitmap) msg.obj;iv.setimagebitmap (Bitmap);}; @Overrideprotected void oncreate (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 void getimage (View view) {Path = et_path.gettext (). toString (). Trim (); if ( Textutils.isempty (path) {Toast.maketext (this, "address cannot be empty", 0). Show (); return;} New thread () {Public void run () {try {url url = new url (path); httpurlconnection conn = (HttpURLConnection) url.openconnection (); conn.setrequestmethod ("GET"); Conn.setreadtimeout (5000); SYSTEM.OUT.PRINTLN ("Response code is-" +conn.getresponsecode ()), if (Conn.getresponsecode () ==200) {//Gets the stream data returned by the server InputStream in = conn.getinputstream ();//parse the returned stream data into a picture bitmap bitmap = Bitmapfactory.decodestream (in);//Use Handler to pass message Message msg = message.obtain (); msg.obj =& nbsp; bitmap;//passed Data handler.sendmessage (msg); In.close ();}} catch (exception e) {e.printstacktrace ();}}. Start ();}}
Note two points:
The creation of the message object uses the Obtain method to achieve object reuse, saving memory overhead.
The message object can use Msg.what = to pass the types of messages, and handler can do different processing depending on the type of message being passed, optimizing the code as follows:
Package com.ccl.getimage;import java.io.inputstream;import java.net.httpurlconnection;import java.net.URL;import android.app.Activity;import android.graphics.Bitmap;import android.graphics.bitmapfactory;import android.os.bundle;import android.os.handler;import android.os.message;import android.text.textutils;import android.view.view;import android.widget.edittext;import android.widget.imageview;import android.widget.toast;public class mainactivity extends activity {protected static final int Success = 0;protected static final int error = 1;protected static final int NETWORK_ERROR = 2;private EditText et_path;private imageview iv;private string path;//using Handler to update the main thread (UI thread) private handler handler = new handler () {Public void handlemessage (message msg) {switch (msg.what) {case SUCCESS:Bitmap bitmap = (Bitmap) msg.obj;iv.setimagebitmap (bitmap); Break;case error:toast.maketext (mainactivity.this, "Get Picture Failed", 0). Show (); Break;case network_error:toast.maketext (mainactivity.this, "Connection to network failed", 0). Show (); break;};}; @Overrideprotected void oncreate (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 void getimage (View view) {Path = et_path.gettext (). toString (). Trim (); if ( Textutils.isempty (path) {Toast.maketext (this, "address cannot be empty", 0). Show (); return;} New thread () {Public void run () {try {url url = new url (path); httpurlconnection conn = (HttpURLConnection) url.openconnection (); &Nbsp; conn.setrequestmethod ("GET"); conn.setreadtimeout (5000); SYSTEM.OUT.PRINTLN ("Response code is-" +conn.getresponsecode ()), if (Conn.getresponsecode () ==200) {//Gets the stream data returned by the server InputStream in = conn.getinputstream ();//parse the returned stream data into a picture bitmap bitmap = Bitmapfactory.decodestream (in);//Use Handler to pass message Message msg = message.obtain (); msg.obj = bitmap;//the data passed msg.what = success;//the type of message passed, handler can do different processing handler.sendmessage (msg) According to the message type; In.close ();} Else{message msg = message.obtain (); Msg.what = error;handler.sendmessage (msg);}} catch (exception e) {message msg = message.obtain ();msg.what = Network_error;handler.sendmessage (msg); E.printstacktrace ();}}. Start ();}}
This article is from the "Android Development Learning Notes" blog, so be sure to keep this source http://282845781.blog.51cto.com/7152559/1748797
Android Connection Network exception: Android.os.NetworkOnMainThreadException