"Android Advanced" using HttpURLConnection to achieve the download and display of images

Source: Internet
Author: User

While we often use open source frameworks that others have developed in development, understanding the underlying implementations of these frameworks allows us to better understand the implementation of functionality.

This article mainly describes the use of HttpURLConnection objects, to achieve the download of picture files, as well as display.

Our idea is to first use httpurlconnection to achieve the download of the picture file, after the download is finished, use handler asynchronous display image.


Because the function is relatively simple, I just paste the code below, the comments are very detailed

/** * Use HttpURLConnection to achieve the download and display of images * * @author Zhaokaiqiang * @time June 9, 2014 */public class Mainactivity extends Activ ity {private Context mcontext;private ImageView image;//loaded successfully private static final int load_success = 1;//load failed private stat IC final int load_error = -1;//for asynchronous display picture private Handler Handler = new Handler () {public void Handlemessage (Message msg) { Switch (msg.what) {///Download Success case load_success://get picture of file Object files = new file (Environment.getexternalstoragedirectory (), "Pic.jpg"); FileInputStream fis = null;try {fis = new FileInputStream (file); Bitmap Bitmap = Bitmapfactory.decodestream (FIS); Image.setimagebitmap (Bitmap);} catch (FileNotFoundException e) {e.printstacktrace ();} break;//Download failed case LOAD_ERROR:Toast.makeText (Mcontext, "load Failed", 0). Show (); break;}};}; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); mcontext = this; Setcontentview (r.layout.activity_main); image = (ImageView) Findviewbyid (r.id.image);} Click event for button public void show (view view) {//Opens a new thread for downloading the picture new thread (new Runnable () {public void run () {getpicture ()}). Start ();} The main method of downloading a picture private void Getpicture () {URL url = null;inputstream is = null; FileOutputStream fos = null;try {//URL address URL of the build image = new URL ("Http://avatar.csdn.net/C/6/8/1_bz419927089.jpg");// Open connection HttpURLConnection conn = (httpurlconnection) url.openconnection ();//Set time-out, 5000 milliseconds, 5 seconds conn.setconnecttimeout ( 5000)///Set the way to get the picture is Getconn.setrequestmethod ("get");//The response code is 200, then the access succeeds if (conn.getresponsecode () = = 200) {//Gets the connected input stream, This input stream is the image input stream is = Conn.getinputstream ();//Build a File object to store the picture file File = new file ( Environment.getexternalstoragedirectory (), "pic.jpg"); fos = new FileOutputStream (file); int len = 0;byte[] buffer = new by te[1024];//writes the input stream to the file we have defined while (len = is.read (buffer)! =-1) {fos.write (buffer, 0, Len);} Will slow flush into the file Fos.flush ();//Tell Handler that the picture has been downloaded successfully handler.sendemptymessage (load_success);}} catch (Exception e) {//Tell handler that the picture has failed to download handler.sendemptymessage (load_error); E.printstacktrace ();} finally {//in the mostThe various streams are closed after the try {if (is! = null) {is.close ()}; if (fos! = null) {Fos.close ();}} catch (Exception e) {handler.sendemptymessage (load_error); E.printstacktrace ();}}}

Layout file

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android"    xmlns:tools= "http// Schemas.android.com/tools "    android:layout_width=" match_parent "    android:layout_height=" Match_parent "    android:gravity= "center"    android:orientation= "vertical" >    <imageview        android:id= "@+id/ Image "        android:layout_width=" 150DP "        android:layout_height=" 150DP "        android:scaletype=" Centercrop "/ >    <button        android:onclick= "show"        android:layout_width= "100DP"        android:layout_height= "100DP"        android:text= "display"/></linearlayout>

Run results



Don't forget to add permissions

<uses-permission android:name= "Android.permission.INTERNET"/>    <uses-permission android:name= " Android.permission.READ_EXTERNAL_STORAGE "/>    <uses-permission android:name=" android.permission.WRITE_ External_storage "/>




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.