-
Notifications
You must be signed in to change notification settings - Fork 30
/
ImageFetcher.java
373 lines (334 loc) · 12.9 KB
/
ImageFetcher.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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.forgottensystems.multiimagechooserV2;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Build;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
/**
* This helper class download images from the Internet and binds those with the
* provided ImageView.
*
* <p>
* It requires the INTERNET permission, which should be added to your
* application's manifest file.
* </p>
*
* A local cache of downloaded images is maintained internally to improve
* performance.
*/
public class ImageFetcher {
private int colWidth;
private long origId;
private ExecutorService executor;
public ImageFetcher() {
executor = Executors.newCachedThreadPool();
}
public void fetch(Integer id, ImageView imageView, int colWidth) {
resetPurgeTimer();
this.colWidth = colWidth;
this.origId = id;
Bitmap bitmap = getBitmapFromCache(id);
if (bitmap == null) {
forceDownload(id, imageView);
} else {
cancelPotentialDownload(id, imageView);
imageView.setImageBitmap(bitmap);
}
}
/**
* Same as download but the image is always downloaded and the cache is not
* used. Kept private at the moment as its interest is not clear.
*/
private void forceDownload(Integer position, ImageView imageView) {
if (position == null) {
imageView.setImageDrawable(null);
return;
}
if (cancelPotentialDownload(position, imageView)) {
BitmapFetcherTask task = new BitmapFetcherTask(imageView.getContext(), imageView);
DownloadedDrawable downloadedDrawable = new DownloadedDrawable(imageView.getContext(), task, origId);
imageView.setImageDrawable(downloadedDrawable);
imageView.setMinimumHeight(colWidth);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
task.executeOnExecutor(executor, position);
} else {
try {
task.execute(position);
} catch (RejectedExecutionException e) {
Log.d("ImageFetcher", "Not downloading: " + e.getMessage());
// Oh :(
}
}
}
}
/**
* Returns true if the current download has been canceled or if there was no
* download in progress on this image view. Returns false if the download in
* progress deals with the same url. The download is not stopped in that
* case.
*/
private static boolean cancelPotentialDownload(Integer position, ImageView imageView) {
BitmapFetcherTask bitmapDownloaderTask = getBitmapDownloaderTask(imageView);
long origId = getOrigId(imageView);
if (bitmapDownloaderTask != null) {
Integer bitmapPosition = bitmapDownloaderTask.position;
if ((bitmapPosition == null) || (!bitmapPosition.equals(position))) {
// Log.d("DAVID", "Canceling...");
MediaStore.Images.Thumbnails.cancelThumbnailRequest(imageView.getContext().getContentResolver(),
origId, 12345);
bitmapDownloaderTask.cancel(true);
} else {
return false;
}
}
return true;
}
/**
* @param imageView
* Any imageView
* @return Retrieve the currently active download task (if any) associated
* with this imageView. null if there is no such task.
*/
private static BitmapFetcherTask getBitmapDownloaderTask(ImageView imageView) {
if (imageView != null) {
Drawable drawable = imageView.getDrawable();
if (drawable instanceof DownloadedDrawable) {
DownloadedDrawable downloadedDrawable = (DownloadedDrawable) drawable;
return downloadedDrawable.getBitmapDownloaderTask();
}
}
return null;
}
private static long getOrigId(ImageView imageView) {
if (imageView != null) {
Drawable drawable = imageView.getDrawable();
if (drawable instanceof DownloadedDrawable) {
DownloadedDrawable downloadedDrawable = (DownloadedDrawable) drawable;
return downloadedDrawable.getOrigId();
}
}
return -1;
}
/**
* The actual AsyncTask that will asynchronously download the image.
*/
class BitmapFetcherTask extends AsyncTask<Integer, Void, Bitmap> {
private Integer position;
private final WeakReference<ImageView> imageViewReference;
private final Context mContext;
public BitmapFetcherTask(Context context, ImageView imageView) {
imageViewReference = new WeakReference<ImageView>(imageView);
mContext = context;
}
/**
* Actual download method.
*/
@Override
protected Bitmap doInBackground(Integer... params) {
position = params[0];
if (isCancelled()) {
return null;
}
Bitmap thumb = MediaStore.Images.Thumbnails.getThumbnail(mContext.getContentResolver(), position, 12345,
MediaStore.Images.Thumbnails.MICRO_KIND, null);
if (isCancelled()) {
return null;
}
if (thumb == null) {
return null;
} else {
if (isCancelled()) {
return null;
} else {
return thumb;
}
}
}
private void setInvisible() {
// Log.d("COLLAGE", "Setting something invisible...");
if (imageViewReference != null) {
final ImageView imageView = imageViewReference.get();
BitmapFetcherTask bitmapDownloaderTask = getBitmapDownloaderTask(imageView);
if (this == bitmapDownloaderTask) {
imageView.setVisibility(View.GONE);
imageView.setClickable(false);
imageView.setEnabled(false);
}
}
}
/**
* Once the image is downloaded, associates it to the imageView
*/
@Override
protected void onPostExecute(Bitmap bitmap) {
if (isCancelled()) {
bitmap = null;
}
addBitmapToCache(position, bitmap);
if (imageViewReference != null) {
ImageView imageView = imageViewReference.get();
BitmapFetcherTask bitmapDownloaderTask = getBitmapDownloaderTask(imageView);
if (this == bitmapDownloaderTask) {
imageView.setImageBitmap(bitmap);
Animation anim = AnimationUtils.loadAnimation(imageView.getContext(), android.R.anim.fade_in);
imageView.setAnimation(anim);
anim.start();
}
} else {
setInvisible();
}
}
}
/**
* A fake Drawable that will be attached to the imageView while the download
* is in progress.
*
* <p>
* Contains a reference to the actual download task, so that a download task
* can be stopped if a new binding is required, and makes sure that only the
* last started download process can bind its result, independently of the
* download finish order.
* </p>
*/
static class DownloadedDrawable extends ColorDrawable {
private final WeakReference<BitmapFetcherTask> bitmapDownloaderTaskReference;
private long origId;
public DownloadedDrawable(Context mContext, BitmapFetcherTask bitmapDownloaderTask, long origId) {
super(Color.TRANSPARENT);
bitmapDownloaderTaskReference = new WeakReference<BitmapFetcherTask>(bitmapDownloaderTask);
this.origId = origId;
}
public long getOrigId() {
return origId;
}
public BitmapFetcherTask getBitmapDownloaderTask() {
return bitmapDownloaderTaskReference.get();
}
}
/*
* Cache-related fields and methods.
*
* We use a hard and a soft cache. A soft reference cache is too aggressively cleared by the
* Garbage Collector.
*/
private static final int HARD_CACHE_CAPACITY = 100;
// private static final int DELAY_BEFORE_PURGE = 10 * 1000; // in milliseconds
// Hard cache, with a fixed maximum capacity and a life duration
private final HashMap<Integer, Bitmap> sHardBitmapCache = new LinkedHashMap<Integer, Bitmap>(
HARD_CACHE_CAPACITY / 2, 0.75f, true) {
/**
*
*/
private static final long serialVersionUID = 3333677999813172362L;
@Override
protected boolean removeEldestEntry(LinkedHashMap.Entry<Integer, Bitmap> eldest) {
if (size() > HARD_CACHE_CAPACITY) {
// Entries push-out of hard reference cache are transferred to
// soft reference cache
sSoftBitmapCache.put(eldest.getKey(), new SoftReference<Bitmap>(eldest.getValue()));
return true;
} else
return false;
}
};
// Soft cache for bitmaps kicked out of hard cache
private final static ConcurrentHashMap<Integer, SoftReference<Bitmap>> sSoftBitmapCache = new ConcurrentHashMap<Integer, SoftReference<Bitmap>>(
HARD_CACHE_CAPACITY / 2);
// private final Handler purgeHandler = new Handler();
// private final Runnable purger = new Runnable() {
// public void run() {
// clearCache();
// }
// };
/**
* Adds this bitmap to the cache.
*
* @param bitmap
* The newly downloaded bitmap.
*/
private void addBitmapToCache(Integer position, Bitmap bitmap) {
if (bitmap != null) {
synchronized (sHardBitmapCache) {
sHardBitmapCache.put(position, bitmap);
}
}
}
/**
* @param position
* The URL of the image that will be retrieved from the cache.
* @return The cached bitmap or null if it was not found.
*/
private Bitmap getBitmapFromCache(Integer position) {
// First try the hard reference cache
synchronized (sHardBitmapCache) {
final Bitmap bitmap = sHardBitmapCache.get(position);
if (bitmap != null) {
// Log.d("CACHE ****** ", "Hard hit!");
// Bitmap found in hard cache
// Move element to first position, so that it is removed last
return bitmap;
}
}
// Then try the soft reference cache
SoftReference<Bitmap> bitmapReference = sSoftBitmapCache.get(position);
if (bitmapReference != null) {
final Bitmap bitmap = bitmapReference.get();
if (bitmap != null) {
// Bitmap found in soft cache
// Log.d("CACHE ****** ", "Soft hit!");
return bitmap;
} else {
// Soft reference has been Garbage Collected
sSoftBitmapCache.remove(position);
}
}
return null;
}
/**
* Clears the image cache used internally to improve performance. Note that
* for memory efficiency reasons, the cache will automatically be cleared
* after a certain inactivity delay.
*/
public void clearCache() {
// sHardBitmapCache.clear();
// sSoftBitmapCache.clear();
}
/**
* Allow a new delay before the automatic cache clear is done.
*/
private void resetPurgeTimer() {
// purgeHandler.removeCallbacks(purger);
// purgeHandler.postDelayed(purger, DELAY_BEFORE_PURGE);
}
}