[Android advanced] Use HttpURLConnection to download and display images

Source: Internet
Author: User

Although we often use open-source frameworks developed by others during development, understanding the underlying implementation of these frameworks allows us to better understand the implementation of functions.

This article describes how to use the HttpURLConnection object to download and display image files.

Our idea is to first use HttpURLConnection to download image files. After the download is complete, use handler to display images asynchronously.

 

Because the function is relatively simple, I only paste the code below, and the comments are very detailed.

 

/*** Use HttpURLConnection to download and display images ** @ author ZhaoKaiQiang * @ time July 22, June 9, 2014 */public class MainActivity extends Activity {private Context mContext; private ImageView image; // private static final int LOAD_SUCCESS = 1; // loading failed private static final int LOAD_ERROR =-1; // for asynchronous display image private Handler handler = new Handler () {public void handleMessage (Message msg) {switch (msg. what) {// case LOAD_S UCCESS: // File object for retrieving images file = new File (Environment. getExternalStorageDirectory (), "pic.jpg"); FileInputStream FCM = null; try {FD = new FileInputStream (file); Bitmap bitmap = BitmapFactory. decodeStream (FS); image. setImageBitmap (bitmap);} catch (FileNotFoundException e) {e. printStackTrace ();} break; // download failure case LOAD_ERROR: Toast. makeText (mContext, "loading failed", 0 ). show (); break ;};};@ Overrideprotected void onC Reate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); mContext = this; setContentView (R. layout. activity_main); image = (ImageView) findViewById (R. id. image) ;}// Button click event public void show (View view) {// enable a new Thread to download the image new Thread (new Runnable () {public void run () {getPicture ();}}). start () ;}// the main method for downloading an image. private void getPicture () {URL url = null; InputStream is = null; FileOutputStream fos = nul L; try {// url of the build image url = new URL ("http://avatar.csdn.net/C/6/8/1_bz419927089.jpg"); // enable the connection HttpURLConnection conn = (HttpURLConnection) url. openConnection (); // set the timeout time, 5000 milliseconds, that is, 5 seconds conn. setConnectTimeout (5000); // you can call GETconn to retrieve an image. setRequestMethod ("GET"); // if the response code is 200, the access is successful if (conn. getResponseCode () = 200) {// gets the input stream of the connection. The input stream is the image input stream is = conn. getInputStream (); // construct a file object for storing the image File = new file (Environment. GetExternalStorageDirectory (), "pic.jpg"); fos = new FileOutputStream (file); int len = 0; byte [] buffer = new byte [1024]; // write the input stream to the defined file while (len = is. read (buffer ))! =-1) {fos. write (buffer, 0, len);} // fl the buffer into the file fos. flush (); // tell handler that the image has been downloaded successfully. sendEmptyMessage (LOAD_SUCCESS) ;}} catch (Exception e) {// tell handler that the image has failed to be downloaded. sendEmptyMessage (LOAD_ERROR); e. printStackTrace ();} finally {// At the end, close various streams try {if (is! = Null) {is. close () ;}if (fos! = Null) {fos. close () ;}} catch (Exception e) {handler. sendEmptyMessage (LOAD_ERROR); e. printStackTrace ();}}}}

Layout File

 

 

     
  
   
  
 

Running result

 

 

Do not forget to add permissions

 

 
     
      
   
  
 


 

 

 

Related Article

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.