1 Packagenet.learn2develop.Networking;2 3 Importandroid.app.Activity;4 ImportAndroid.os.Bundle;5 6 Importjava.io.IOException;7 ImportJava.io.InputStream;8 9 Importjava.net.HttpURLConnection;Ten ImportJava.net.URL; One Importjava.net.URLConnection; A ImportAndroid.util.Log; - - ImportAndroid.widget.ImageView; the ImportAndroid.widget.Toast; - ImportAndroid.graphics.Bitmap; - Importandroid.graphics.BitmapFactory; - ImportAndroid.os.AsyncTask; + Public classNetworkingactivityextendsActivity { - + ImageView img; A at PrivateInputStream openhttpconnection (String urlstring)throwsIOException - { -InputStream in =NULL; - intResponse =-1; - -URL url =NewURL (urlstring); inURLConnection conn =url.openconnection (); - to if(! (Conninstanceofhttpurlconnection)) + Throw NewIOException ("Not an HTTP connection"); - Try{ theHttpURLConnection Httpconn =(httpurlconnection) conn; *Httpconn.setallowuserinteraction (false); $Httpconn.setinstancefollowredirects (true);Panax NotoginsengHttpconn.setrequestmethod ("GET"); - Httpconn.connect (); theResponse =Httpconn.getresponsecode (); + if(Response = =HTTPURLCONNECTION.HTTP_OK) { Ain =Httpconn.getinputstream (); the } + } - Catch(Exception ex) $ { $LOG.D ("Networking", Ex.getlocalizedmessage ()); - Throw NewIOException ("Error connecting"); - } the returnIn ; - }Wuyi the PrivateBitmap downloadimage (String URL) - { WuBitmap Bitmap =NULL; -InputStream in =NULL; About Try { $in =openhttpconnection (URL); -Bitmap =Bitmapfactory.decodestream (in); - in.close (); -}Catch(IOException E1) { ALOG.D ("Networkingactivity", E1.getlocalizedmessage ()); + } the returnbitmap; - } $ the the Private classDownloadimagetaskextendsAsynctask<string, Void, bitmap> { the protectedBitmap doinbackground (String ... urls) { the returnDownloadimage (urls[0]); - } in the protected voidOnPostExecute (Bitmap result) { theImageView img =(ImageView) Findviewbyid (r.id.img); About Img.setimagebitmap (result); the } the } the + @Override - Public voidonCreate (Bundle savedinstancestate) { the Super. OnCreate (savedinstancestate);Bayi Setcontentview (r.layout.main); the the NewDownloadimagetask (). Execute ("Http://www.mayoff.com/5-01cablecarDCP01934.jpg"); - } -}
Because the Downloadimage () method is synchronous-this means that no control is returned until the picture is downloaded-so calling it directly causes the active UI to freeze, using Asynctask to allow background tasks to be performed in a separate thread, and then returning the results in the UI thread.
Android Network Download pictures