Method of Using this module: when creating a loadimageasynctask object, you must pass in an implementation class of the loadimageasynctaskcallback interface. Actually, you can call this method to complete the operations before and after image loading.
Public class loadimageasynctask extends asynctask <string, void, bitmap> {loadimageasynctaskcallback callback; Public loadimageasynctask (loadimageasynctaskcallback) {super (); this. response = callback;} public interface loadimageasynctaskcallback {public void beforeloadimage (); Public void afterloadimage (Bitmap bitmap);} @ overrideprotected void onpreexecute () {loadimageasynctaskcallback. beforeloadimage (); super. onpreexecute () ;}@ overrideprotected void onpostexecute (Bitmap result) {loadimageasynctaskcallback. afterloadimage (result); super. onpostexecute (result) ;}@ overrideprotected bitmap doinbackground (string... params) {If (Params. length> = 1) {try {string Path = Params [0]; final file = new file (environment. getexternalstoragedirectory () + "/cache", urlencoder. encode (PATH); If (file. exists () {fileinputstream is = new fileinputstream (File); system. out. println ("using SD card to cache images"); Return bitmapfactory. decodestream (is);} else {URL url = new URL (PATH); httpurlconnection conn = (httpurlconnection) URL. openconnection (); inputstream = Conn. getinputstream (); Final Bitmap bitmap = bitmapfactory. decodestream (inputstream); New thread () {@ overridepublic void run () {try {outputstream stream = new fileoutputstream (File); bitmap. compress (compressformat. JPEG, 100, stream);} catch (filenotfoundexception e) {e. printstacktrace ();}}}. start (); system. out. println ("use download image"); Return bitmap ;}} catch (exception e) {e. printstacktrace (); return NULL ;}} else {return NULL ;}}}
Soft reference of images: soft reference can greatly improve the efficiency of image loading:
Private Map <string, softreference <bitmap> map = new hashmap <string, softreference <bitmap> (); // define member variables
// In the code: if (map. containsKey (imagePath) {SoftReference <Bitmap> softReference = map. get (imagePath); if (softReference! = Null) {Bitmap bitmap = softReference. get (); if (bitmap! = Null) {System. out. println ("using memory to cache images"); book_img.setImageBitmap (bitmap);} else {loadImage (book_img, imagePath); // use non-soft reference to load images .}} else {loadImage (book_img, imagePath) ;}} else {loadImage (book_img, imagePath);} private void loadImage (final ImageView book_img, final String imagePath) {new LoadImageAsyncTask (new LoadImageAsyncTaskCallback () {public void beforeLoadImage () {} public void afterLoadImage (Bitm Ap bitmap) {if (bitmap! = Null) {book_img.setImageBitmap (bitmap); map. put (imagePath, new SoftReference <Bitmap> (bitmap); // when loading an image using a non-soft reference method, save the image to the software reference // in use .20.20.20.20..exe cute (imagePath );}