1. You must open a sub-thread to operate the time-consuming Operation android.os.NetworkOnMainThreadException
New Thread (New Runnable () {@Overridepublic void Run () {//TODO auto-generated method stubtry {updatefile = Environment.get Externalstoragedirectory () + "/3530.jpg";//downloadupdatefile ("http://image.anzimall.com/3530/3530_K21D_app_V2.3 _2015050528.bin ", updatefile);d ownloadupdatefile (" http://img1.cache.netease.com/catchpic/F/FC/ Fcc085159b92c5ee4fddb9618166051e.jpg ", updatefile);} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace (); Android.os.NetworkOnMainThreadExceptionSystem.out.println (e.tostring () + "");}}). Start ();
2. After throwing an exception, be sure to print the exception to see the specific information of the exception. System.out.println (e.tostring () + "");
public static long Downloadupdatefile (string down_url, String file) throws Exception {int downloadcount = 0;//already downloaded size Inpu TStream Inputstream;outputstream OutputStream; URL url = new URL (down_url); HttpURLConnection httpurlconnection = (httpurlconnection) url.openconnection (); httpurlconnection.setconnecttimeout Httpurlconnection.setreadtimeout (5000);//Get the downloaded file Size//totalsize = Httpurlconnection.getcontentlength (); (Httpurlconnection.getresponsecode () = = 404) {throw new Exception ("fail!"); /This place should add a download failed processing, however, because we added a try---catch, has processed exception,//so do not have to process}InputStream = Httpurlconnection.getinputstream ();File FILE_OK = new file; outputstream = new FileOutputStream (FILE_OK);//files overwrite byte buffer[] = new Byte[1024];int R Eadsize = 0;while ((readsize = inputstream.read (buffer))! =-1) {outputstream.write (buffer, 0, readsize);d Ownloadcount + = readsize;//always gets the size downloaded to}if (httpurlconnection! = null) {Httpurlconnection.disconnect ();} Inputstream.close (); Outputstream.close (); return downloadcount;}
The main thread must not put time-consuming operation, you have to open a sub-thread, such as download files, or will not let you get input stream-error display android.os.NetworkOnMainThreadException