修改后的代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import  java.io.InputStream;
import  java.lang.ref.WeakReference;
import  java.net.HttpURLConnection;
import  java.net.URL;
import  android.graphics.Bitmap;
import  android.graphics.BitmapFactory;
import  android.os.AsyncTask;
import  android.util.Log;
import  android.widget.ImageView;
/**
  * @类名:ImageDownloader
  * @功能描述:优化的ImageDownloader, 不带缓存,在线下载,用户头像请使用。
  * @作者: William Xu
  * @创建日期:2013-6-7
  * @修改人:
  * @修改日期:
  * @修改备注:
  * @版本号:1.0
  */
public  class  ImageDownloader {
     public  void  download(String url, ImageView imageView) {
         BitmapDownloaderTask task =  new  BitmapDownloaderTask(imageView);
         task.execute(url);
     }
     class  BitmapDownloaderTask  extends  AsyncTask<String, Void, Bitmap> {
           
         private  final  WeakReference<ImageView> imageViewReference;  // 使用WeakReference解决内存问题
         public  BitmapDownloaderTask(ImageView imageView) {
             imageViewReference =  new  WeakReference<ImageView>(imageView);
         }
         @Override
         protected  Bitmap doInString...  params) {  // 实际的下载线程,内部其实是concurrent线程,所以不会阻塞
             Bitmap bitmap =  null ;
             try  {
                 URL imageUrl =  new  URL(params[ 0 ]);
                 HttpURLConnection conn = (HttpURLConnection) imageUrl
                         .openConnection();
                 conn.setConnectTimeout( 30000 );
                 conn.setReadTimeout( 30000 );
                 conn.setInstanceFollowRedirects( true );
                 InputStream is = conn.getInputStream();
                 bitmap = BitmapFactory.decodeStream(is);
             catch  (Exception ex) {
                 Log.e( "" ,
                         "getBitmap catch Exception...\nmessage = "
                                 + ex.getMessage());
             }
             return  bitmap;
         }
         @Override
         protected  void  onPostExecute(Bitmap bitmap) {  // 下载完后执行的
             if  (isCancelled()) {
                 bitmap =  null ;
             }
             if  (imageViewReference !=  null ) {
                   
                 ImageView imageView = imageViewReference.get();
                   
                 if  (imageView !=  null  && bitmap !=  null ) {
                       
                     imageView.setImageBitmap(bitmap);  // 下载完设置imageview为刚才下载的bitmap对象
                 }
             }
         }
     }
}

本文转自william_xu 51CTO博客,原文链接:http://blog.51cto.com/williamx/1218518,如需转载请自行联系原作者