-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMemoryLoader.java
80 lines (69 loc) · 2.08 KB
/
MemoryLoader.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
package wags.gravatar;
import android.graphics.Bitmap;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
public class MemoryLoader {
private static final String TAG = "MemoryLoader";
private Map<String, Bitmap> cache =
Collections.synchronizedMap(new LinkedHashMap<String, Bitmap>(10, 1.5f, true));
private long size = 0;
private long limit = 1000000;
public MemoryLoader() {
setLimit(Runtime.getRuntime().maxMemory() / 4);
}
public void setLimit(long new_Limit) {
limit = new_Limit;
}
public Bitmap get(String id) {
try {
if (!cache.containsKey(id)) {
return null;
}
return cache.get(id);
} catch (NullPointerException e) {
e.printStackTrace();
return null;
}
}
public void put(String id, Bitmap bitmap) {
try {
if (cache.containsKey(id)) {
size -= getSizeInBytes(cache.get(id));
}
cache.put(id, bitmap);
size += getSizeInBytes(bitmap);
checkSize();
} catch (Throwable e) {
e.printStackTrace();
}
}
private void checkSize() {
if (size > limit) {
Iterator<Map.Entry<String, Bitmap>> iter = cache.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, Bitmap> entry = iter.next();
size -= getSizeInBytes(entry.getValue());
iter.remove();
if (size <= limit) {
break;
}
}
}
}
public void clear() {
try {
cache.clear();
size = 0;
} catch (NullPointerException e) {
e.printStackTrace();
}
}
long getSizeInBytes(Bitmap bitmap) {
if (bitmap == null) {
return 0;
}
return bitmap.getRowBytes() * bitmap.getHeight();
}
}