Android.os.NetworkOnMainThreadException

Source: Internet
Author: User

Networkonmainthreadexception
becomes unresponsive. To avoid it is should call it on another thread. Hence Asynctask is better.


Networkonmainthreadexception throws this exception when performing network operations in the main thread;

You should call the "Sendfeedback" method of "Asynctask" to perform network operations, and when the Web server spends a lot of time responding to the main thread and becomes dull, in order to avoid this situation, using "asynctask" is better

 PackageCom.example.lj.imagedemo;ImportAndroid.graphics.Bitmap;Importandroid.graphics.BitmapFactory;ImportAndroid.os.AsyncTask;Importandroid.support.v7.app.AppCompatActivity;ImportAndroid.os.Bundle;ImportAndroid.util.Log;ImportAndroid.widget.ImageView;Importjava.io.IOException;ImportJava.io.InputStream;Importjava.net.HttpURLConnection;ImportJava.net.URL; Public classMainactivityextendsappcompatactivity {Private Static FinalString TAG = "Mainactivity"; PrivateImageView ImageView; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); Try{ImageView=(ImageView) Findviewbyid (R.id.imageview);/*New Thread (new Runnable () {@Override public void run () { Picture resource String url = "HTTP://S16.SINAIMG.CN/ORIGNAL/89429F6DHB99B4903EBCF&690 ";                    Get the pictures available Bitmap Bitmap = gethttpbitmap (URL);                    if (bitmap = = null) {LOG.I (TAG, "bitmap is null");                }//Display Imageview.setimagebitmap (bitmap); }}). Start ();*/            NewDownloadurlbitmap (). Execute ("Http://192.168.118.120:8888/img/dn1.jpg"); } Catch(Exception e) {e.printstacktrace (); }    }    Private classDownloadurlbitmapextendsAsynctask<string, Void, bitmap>{@OverrideprotectedBitmap doinbackground (String ... params) {returnLoadimagefromnetwork (params[0]); } @Overrideprotected voidOnPostExecute (Bitmap Bitmap) {imageview.setimagebitmap (BITMAP); }    }    PrivateBitmap loadimagefromnetwork (String url) {//get the pictures availableBitmap Bitmap =simplenetworkimage (URL); if(Bitmap = =NULL) {log.i (TAG,"Bitmap is null"); }        returnbitmap; }     PublicBitmap simplenetworkimage (String url) {Bitmap PNGBM=NULL; Try{URL Picurl=Newurl (URL); PNGBM=Bitmapfactory.decodestream (Picurl.openstream ()); } Catch(IOException e) {e.printstacktrace (); }        returnPNGBM; }    /*** Get the net picture resources * *@paramURL *@return     */     PublicBitmap gethttpbitmap (String url) {URL myfileurl; Bitmap Bitmap=NULL; Try{Myfileurl=Newurl (URL); //Get ConnectedHttpURLConnection conn =(HttpURLConnection) myfileurl.openconnection (); //set time-out to 6000 milliseconds, Conn.setconnectiontiem (0), no time limitConn.setconnecttimeout (6000); //connection settings Get Data flowConn.setdoinput (true); //do not use cacheConn.setusecaches (false); //This sentence is dispensable, no influence//Conn.connect (); //get the data streamInputStream is =Conn.getinputstream (); //parse to get the pictureBitmap =Bitmapfactory.decodestream (IS); //Turn off Data flowIs.close (); } Catch(Exception e) {e.printstacktrace (); }        returnbitmap; }}

Android.os.NetworkOnMainThreadException

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.