1 | public class ImageLoader { |
2 | // 图片缓存 |
3 | LruCache< String , Bitmap > mImageCache ; |
4 | // 线程池,线程数量为 CPU 的数量 |
5 | ExecutorService mExecutorService = Executors . newFixedThreadPool( Runtime . getRuntime() . availableProcessors()) ; |
6 | |
7 | // 构造方法 |
8 | public ImageLoader () { |
9 | // 初始化图片缓存 |
10 | initImageCache() ; |
11 | } |
12 | |
13 | private void initImageCache () { |
14 | // 计算可使用的最大内存 |
15 | final int maxMemory = ( int ) ( RunTime . getRuntime() . maxMemory() / 1024 ) ; |
16 | // 取四分之一的可用内存作为缓存 |
17 | final int cacheSize = maxMemory / 4 ; |
18 | |
19 | mImageCache = new LruCache< String , Bitmap > (cacheSize) { |
20 | // 重写 LruCache 的 sizeOf 方法 |
21 | @Override |
22 | protected int sizeOf ( String key , Bitmap bitmap ) { |
23 | return bitmap . getRowBytes() * bitmap . getHeight() / 1024 ; |
24 | } |
25 | } ; |
26 | } |
27 | |
28 | /** |
29 | * 显示图片 |
30 | */ |
31 | public void displayImage ( final String url , final ImageView imageView ) { |
32 | imageView . setTag(url) ; |
33 | // 使用线程池 |
34 | mExecutorService . submit( |
35 | new Runnable () { |
36 | @Override |
37 | public void run () { |
38 | Bitmap bitmap = downloadImage(url) ; |
39 | if ( null == bitmap) return ; |
40 | if (imageView . getTag() . equals(url)) |
41 | imageView . setImageBitmap(bitmap) ; // 显示下载的图片 |
42 | // 存入缓存 |
43 | mImageCache . put(url, bitmap) ; |
44 | } |
45 | } |
46 | ) ; |
47 | } |
48 | |
49 | /** |
50 | * 下载图片,在显示图片方法中调用 |
51 | */ |
52 | public Bitmap downloadImage ( String imageUrl ) { |
53 | Bitmap bitmap = null ; |
54 | try { |
55 | URL url = new URL (imageUrl) ; |
56 | final HttpURLConnection conn = ( HttpURLConnection ) url . openConnection() ; |
57 | bitmap = BitmapFactory . decodeStream(conn . getInputStream()) ; |
58 | conn . disconnect() ; |
59 | } catch ( Exception e){ |
60 | e . printStackTrace() ; |
61 | } |
62 | return bitmap ; |
63 | } |
64 | } |