-
Notifications
You must be signed in to change notification settings - Fork 14
/
AsyncImageLoader.java
293 lines (258 loc) · 7.92 KB
/
AsyncImageLoader.java
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v4.util.LruCache;
import android.widget.ImageView;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* AsyncImageLoader
*
* @author: onlylemi
*/
public class AsyncImageLoader {
private static AsyncImageLoader mLoader;
private static Context mContext;
// 内存缓存默认 5M
static final int MEMORY_CACHE_DEFAULT_SIZE = 5 * 1024 * 1024;
// 文件缓存默认 50M
static final int DISK_CACHE_DEFAULT_SIZE = 50 * 1024 * 1024;
// 内存缓存
private LruCache<String, Bitmap> mMemoryCache;
// 磁盘缓存
private DiskLruCache mDiskCache;
public AsyncImageLoader(Context context) {
mContext = context.getApplicationContext();
initMemoryCache();
initDiskCache(mContext);
}
public static AsyncImageLoader with(Context context) {
if (null == mLoader) {
mLoader = new AsyncImageLoader(context);
}
return mLoader;
}
/**
* 初始化内存缓存
*/
private void initMemoryCache() {
int maxMemory = (int) Runtime.getRuntime().maxMemory();
int cacheSize = maxMemory / 8;
mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
@Override
protected int sizeOf(String key, Bitmap bitmap) {
return bitmap.getByteCount();
}
};
}
/**
* 初始化磁盘缓存
*/
private void initDiskCache(Context context) {
try {
File cacheDir = AppUtils.getDiskCacheDir(context, "img");
if (!cacheDir.exists()) {
cacheDir.mkdirs();
}
mDiskCache = DiskLruCache.open(cacheDir, AppUtils.getAppVersion(App.getContext()), 1,
DISK_CACHE_DEFAULT_SIZE);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 从内存缓存中获取图片
*
* @param key
* @return
*/
private Bitmap getBitmapFromMemory(String key) {
return mMemoryCache.get(key);
}
/**
* 加入到缓存中
*
* @param key
* @param bitmap
*/
private void putBitmapToMemory(String key, Bitmap bitmap) {
if (getBitmapFromMemory(key) == null) {
mMemoryCache.put(key, bitmap);
}
}
/**
* 从磁盘中获取
*
* @param key
* @return
*/
private Bitmap getBitmapFromDisk(String key) {
Bitmap bitmap = null;
try {
DiskLruCache.Snapshot snapshot = mDiskCache.get(hashKeyForDisk(key));
if (null != snapshot) {
InputStream in = snapshot.getInputStream(0);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.RGB_565;
bitmap = BitmapFactory.decodeStream(in, null, options);
}
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
/**
* 加入到磁盘中
*
* @param key
* @param bitmap
*/
private void putBitmapToDisk(String key, Bitmap bitmap) {
try {
DiskLruCache.Editor editor = mDiskCache.edit(hashKeyForDisk(key));
if (null != editor) {
OutputStream output = editor.newOutputStream(0);
if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, output)) {
editor.commit();
} else {
editor.abort();
}
mDiskCache.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 加载图片
*
* @param imageView
* @param url
* @return 如需网络下载,则返回true
*/
public boolean loadImage(final ImageView imageView, String url) {
return loadImage(imageView, url, true);
}
/**
* 加载图片
*
* @param imageView
* @param url
* @param isIdle 在listview中,监听listview的滚动状态,滚动为false,不滚动为true
* @return
*/
public boolean loadImage(final ImageView imageView, String url, boolean isIdle) {
imageView.setTag(url);
Bitmap bitmap = getBitmapFromMemory(url);
if (null != bitmap) {
imageView.setImageBitmap(bitmap);
return false;
}
// 再从磁盘中获取
bitmap = getBitmapFromDisk(url);
if (null != bitmap) {
putBitmapToMemory(url, bitmap);
imageView.setImageBitmap(bitmap);
return false;
}
// 下载图片
if (isIdle) {
new ImageDownloadTask(imageView).execute(url);
}
return true;
}
/**
* 异步下载图片
*/
private class ImageDownloadTask extends AsyncTask<String, Integer, Bitmap> {
private final String TAG = ImageDownloadTask.class.getSimpleName();
private String imgUrl;
private ImageView imageView;
private int resId;
public ImageDownloadTask(ImageView imageView) {
this.imageView = imageView;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Bitmap doInBackground(String... params) {
imgUrl = params[0];
// 下载图片
Bitmap bitmap = downloadBitmap(imgUrl);
// 加入缓存
putBitmapToMemory(imgUrl, bitmap);
// 加入磁盘
putBitmapToDisk(imgUrl, bitmap);
return bitmap;
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(Bitmap bitmap) {
if (null != bitmap && null != imageView) {
// 通过 tag 来防止图片错位
if (null != imageView.getTag() && imageView.getTag().equals(imgUrl)) {
imageView.setImageBitmap(bitmap);
}
}
}
/**
* 下载image
*
* @param imgUrl
* @return
*/
private Bitmap downloadBitmap(String imgUrl) {
Bitmap bitmap = null;
HttpURLConnection conn = null;
try {
URL url = new URL(imgUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5 * 1000);
conn.setReadTimeout(10 * 1000);
conn.connect();
bitmap = BitmapFactory.decodeStream(conn.getInputStream());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != conn) {
conn.disconnect();
}
}
return bitmap;
}
}
private String hashKeyForDisk(String key) {
String cacheKey;
try {
final MessageDigest mDigest = MessageDigest.getInstance("MD5");
mDigest.update(key.getBytes());
cacheKey = bytesToHexString(mDigest.digest());
} catch (NoSuchAlgorithmException e) {
cacheKey = String.valueOf(key.hashCode());
}
return cacheKey;
}
private String bytesToHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
String hex = Integer.toHexString(0xFF & bytes[i]);
if (hex.length() == 1) {
sb.append('0');
}
sb.append(hex);
}
return sb.toString();
}
}