From: http://www.cnblogs.com/dwinter/archive/2012/01/30/2331556.html
Public class bitmapcache {
Static private bitmapcache cache;
/** Storage of chche content */
Private hashtable <integer, mysoftref> hashrefs;
/** Spam reference Queue (if the referenced object has been recycled, the reference will be saved to the queue )*/
Private referencequeue <bitmap> q;
/**
* Inherits softreference, so that each instance has a recognizable identifier.
*/
Private class mysoftref extends softreference <bitmap> {
Private integer _ key = 0;
Public mysoftref (bitmap BMP, referencequeue <bitmap> q, int key ){
Super (BMP, q );
_ Key = key;
}
}
Private bitmapcache (){
Hashrefs = new hashtable <integer, mysoftref> ();
Q = new referencequeue <bitmap> ();
}
/**
* Obtain the cache instance
*/
Public static bitmapcache getinstance (){
If (Cache = NULL ){
Cache = new bitmapcache ();
}
Return cache;
}
/**
* Reference an instance of a bitmap object in soft reference mode and save the reference.
*/
Private void addcachebitmap (bitmap BMP, integer key ){
Cleancache (); // clear spam reference
Mysoftref ref = new mysoftref (BMP, Q, key );
Hashrefs. Put (Key, ref );
}
/**
* Obtain the instance of the corresponding bitmap object based on the image resource ID under the specified drawable (you can obtain it from the network or local path as needed ).
*/
Public bitmap getbitmap (INT resid, context ){
Bitmap BMP = NULL;
// Check whether soft references of the bitmap instance exist in the cache. If so, obtain them from soft references.
If (hashrefs. containskey (resid )){
Mysoftref ref = (mysoftref) hashrefs. Get (resid );
BMP = (Bitmap) ref. Get ();
}
// If there is no soft reference, or the Instance obtained from the soft reference is null, re-build an instance,
// Save the soft reference for the new instance
If (BMP = NULL ){
// Decodestream directly calls JNI> nativedecodeasset () to complete decode,
// You do not need to use createbitmap on the Java layer to save the Java Layer Space.
BMP = bitmapfactory. decodestream (context. getresources ()
. Openrawresource (resid ));
This. addcachebitmap (BMP, resid );
}
Return BMP;
}
Private void cleancache (){
Mysoftref ref = NULL;
While (ref = (mysoftref) Q. Poll ())! = NULL ){
Hashrefs. Remove (ref. _ key );
}
}
/**
* Clear all content in the cache
*/
Public void upload AchE (){
Cleancache ();
Hashrefs. Clear ();
System. GC ();
System. runfinalization ();
}
}