Android to implement multithreading download pictures _android

Source: Internet
Author: User
Tags file url static class

A lot of times we need to download the images on the remote server on the Android device to display, and today we'll sort out two better ways of downloading the remote pictures.

method One, directly through the HTTP class provided by Android to access the remote server, where Androidhttpclient is the new method in SDK 2.2, API level 8, you need to note that static access can be directly called, If the SDK version is lower, you can consider Apache's HTTP library, and of course httpurlconnection or URLConnection.

 Static Bitmap downloadbitmapbycwj (String URL) {Final androidhttpclient client = androidhttpclient.newinstance ("Androi 
 D123 "); 

 Final HttpGet getrequest = new HttpGet (URL); 
  try {httpresponse response = Client.execute (getrequest); 
  Final int statusCode = Response.getstatusline (). Getstatuscode (); if (StatusCode!= httpstatus.sc_ok) {log.e ("Cwjdebug", "Error" + StatusCode + "while retrieving bitmap from" + URL 
   ); 
  return null; 
  Final httpentity entity = response.getentity (); 
   if (entity!= null) {InputStream inputstream = null; 
    try {InputStream = Entity.getcontent (); 
    Final Bitmap Bitmap = Bitmapfactory.decodestream (InputStream); 
   return bitmap; 
    finally {if (InputStream!= null) {inputstream.close (); 
   } entity.consumecontent (); 
  A catch (Exception e) {getrequest.abort ()); 
 LOG.E ("Android123debug", "Error while retrieving bitmap from" + URL, e.tostring ()); finally {if (ClienT!= null) {client.close (); 
} return null;
 }

Here the Android Development network reminds you that the Decodestream method of the Bitmapfactory class does not get complete data when the network times out or is slow. Here we enforce the data in the flush stream by inheriting the skip method of the FilterInputStream class, and the main principle is to check whether to the end of the file and tell the HTTP class whether to continue.

Static Class Flushedinputstream extends FilterInputStream {public 
 flushedinputstream (InputStream inputstream) { 
  super (InputStream); 
 } 

 @Override public 
 Long Skip (long N) throws IOException { 
  long totalbytesskipped = 0L; 
  while (Totalbytesskipped < n) { 
   long bytesskipped = In.skip (n-totalbytesskipped); 
   if (bytesskipped = = 0L) { 
     int byte = read (); 
     if (Byte < 0) {break 
      ;//We reached EOF 
     } else { 
      bytesskipped = 1;//We read one byte 
     } 
   }
   totalbytesskipped + + bytesskipped; 
  } 
  Return totalbytesskipped 
 } 
} 

method Two, Asynctask Asynchronous task

Starting with the Android 1.5 firmware Google provides a Asynctask class to help developers deal with asynchronous downloads, which, as opposed to thread, can run in the UI thread, and their internal implementations are derived from the concurrency package concurrent that started in Java 5 , the overall implementation is more reliable is a little bit more resource consumption. But it's easier to use than that. Download the picture class Imagedownloader class download method can be very good for the implementation of UI display operations, parameter one URL for the remote server file URL, the second parameter is ImageView object, You can directly let ImageView display the downloaded remote picture.

 public class Imagedownloader {public 

 void download (String URL, ImageView imageview) { 
   bitmapdownloadertask task = new Bitmapdownloadertask (ImageView); 
   Task.execute (URL);}} 

 

With regard to the specific Asynctask class implementation, given that the picture may be large, in order to give the JVM adequate space to store, here Android123 recommends that you use a weak reference to save the ImageView object.

Class Bitmapdownloadertask extends Asynctask<string, Void, bitmap> { 
 private String URL; 
 Private final weakreference<imageview> imageviewreference; Troubleshoot memory problems with WeakReference public 

 bitmapdownloadertask (ImageView imageview) { 
  imageviewreference = new Weakreference<imageview> (ImageView); 
 } 

 @Override 
 protected Bitmap doinbackground (String ... params) {//actual download thread, inside is actually a concurrent thread, so it won't block return 
 
   Downloadbitmap (Params[0]); 

 @Override 
  protected void OnPostExecute (Bitmap Bitmap) {// 
  if (iscancelled ()) {Bitmap = null;< after download 
   c14/>} 

  if (imageviewreference!= null) { 
   ImageView ImageView = Imageviewreference.get (); 
   if (ImageView!= null) { 
    imageview.setimagebitmap (bitmap);////Download Settings ImageView for the bitmap object you just downloaded 
   }} 
  } 
}

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.