Online on this aspect of the article also a lot, the basic idea is thread + cache to solve. Some optimizations are presented below:
1, the use of thread pool
2, Memory cache + file cache
3, the memory cache in many of the internet is to use softreference to prevent heap overflow, here strictly limit only the maximum JVM memory 1/4
4, to download the picture to scale proportionally to reduce memory consumption
Specific code inside the description. Put the code Memorycache.java of the memory cache class first:
public class MemoryCache {private static final String TAG = "MemoryCache"; When put into cache it is a synchronous operation//Linkedhashmap the last parameter of the constructor method True means that the elements in this map will be ranked by the number of recent usage, that is, LRU//The advantage is that if you want to replace the elements in the cache, you first iterate through the least recent Replace with elements to improve efficiency private map<string, bitmap> cache = collections. Synchronizedmap (New linkedhashmap& Lt
String, Bitmap> (1.5f, true)); The byte occupied by the picture in the cache, the initial 0, which will pass this variable to strictly control the heap memory occupied by the cache private long size = 0;//Current allocated size//cache can only occupy maximum heap memory p Rivate long limit = 1000000;//max memory in bytes public memorycache () {//Use 25% of available H
EAP Size Setlimit (Runtime.getruntime (). MaxMemory ()/4);
} public void Setlimit (long new_limit) {limit = New_limit; LOG.I (TAG, "memorycache'll use up to" + limit/1024. /1024.
+ "MB");
Bitmap get (String id) {try {if!cache.containskey (ID)) REturn null;
return Cache.get (ID);
catch (NullPointerException ex) {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 th) {th.printstacktrace ();
}/** * Strictly controls heap memory, if more than the most recent least used image cache * */private void checksize () {
LOG.I (TAG, "cache size=" + size + "length=" + cache.size ()); if (Size > Limit) {//First traverse the least recently used element iterator<entry<string, bitmap>> iter = Cach
E.entryset (). iterator ();
while (Iter.hasnext ()) {entry<string, bitmap> Entry = Iter.next (); Size = Getsizeinbytes (entry.GetValue ());
Iter.remove ();
if (size <= limit) break; LOG.I (TAG, "clean cache.")
New size "+ cache.size ());
} public void Clear () {cache.clear (); /** * Image Memory * @param bitmap * @return/Long getsizeinbytes (bitmap
Bitmap) {if (bitmap = null) return 0;
return Bitmap.getrowbytes () * Bitmap.getheight (); }
}