Asynchronous download of images and image caching

Source: Internet
Author: User
Functions:

The process is as follows:

Remoteimageviewactivity:

    public class RemoteImageViewActivity extends Activity {          /** Called when the activity is first created. */          @Override          public void onCreate(Bundle savedInstanceState) {              super.onCreate(savedInstanceState);              setContentView(R.layout.main);                    RemoteImageView img = (RemoteImageView) findViewById(R.id.remote_img);              img.setDefaultImage(R.drawable.ic_launcher);              img.setImageUrl("http://img2.kwcdn.kuwo.cn:81/star/albumcover/120/7/8/83787_1323997225.jpg");          }                @Override          protected void onPause() {              // TODO Auto-generated method stub              super.onPause();          }      }  

Imagecache:

Public class imagecache extends weakhashmap <string, bitmap> {/*** determines whether the URL exists * @ Param URL * @ return */Public Boolean iscached (string URL) {return containskey (URL) & get (URL )! = NULL ;}}

Remoteimageapplication:

    public class RemoteImageApplication extends Application {                public static final String TAG = "RemoteImageApplication";                private static RemoteImageApplication application;                private ImageCache mImageCache;                public SharedPreferences prefs = null;                          public static RemoteImageApplication getInstance() {              return application;          }                @Override          public void onCreate() {              // TODO Auto-generated method stub              super.onCreate();                    application = this;                    mImageCache = new ImageCache();                    prefs = PreferenceManager.getDefaultSharedPreferences(this);          }                public ImageCache getImageCache() {              return mImageCache;          }      }  

Remotesettings:

Public class remotesettings {public static final string cache_size = "cache_size"; // The image cache size is retained. If the size is exceeded, the cache is automatically cleared .}

Remoteimageview:

Public class remoteimageview extends imageview {private context mcontext; Private Static int mcachesize = 150; // set the cache size. Private Static final int max_failures = 3; // Number of download attempts private int mfailure; // Number of download attempts private string murl; // The current downloaded URL private string mcurrentlygrabbedurl; // URL private final static string jamendo_dir = "android/data/COM. teleca. jamendo "; // File Cache path. private Final Static long Mbit/s = 1073741824; Public remoteimageview (context, attributeset attrs, int defstyle) {super (context, ATT RS, defstyle); mcontext = context;} public remoteimageview (context, attributeset attrs) {super (context, attrs); mcontext = context;} public remoteimageview (context) {super (context); mcontext = context;}/*** sets the default image */Public void setdefaultimage (integer resid) {setimageresource (resid );} /*** set the image to be asynchronously loaded */Public void setimageurl (string URL) {// download failed to retry. If the number of retries exceeds the specified limit, directly Return. If (murl! = NULL & murl. Equals (URL) & (mcurrentlygrabbedurl = NULL | (mcurrentlygrabbedurl! = NULL &&! Mcurrentlygrabbedurl. equals (URL) {mfailure ++; If (mfailure> max_failures) {log. E (remoteimageapplication. tag, "failed to download the image address:" + URL); Return ;}} else {murl = URL; mfailure = 0 ;} imagecache = remoteimageapplication. getinstance (). getimagecache (); If (imagecache. iscached (URL) {setimagebitmap (imagecache. get (URL);} else {// If the cache does not exist in the memory, search for it from the file. string filename = converturltofilen Ame (URL); // process the file name string filepath = getdirectory (filename); // obtain the cache folder directory string pathfilename = filepath + "/" + filename; // file pathfile = new file (pathfilename); If (! Pathfile. exists () {try {pathfile. createnewfile ();} catch (ioexception e) {log. D (remoteimageapplication. tag, "failed to create image file:" + pathfilename) ;}} bitmap tbmp = bitmapfactory. decodefile (pathfilename); If (tbmp = NULL) {log. D (remoteimageapplication. tag, "image file does not exist, start to download"); try {New downloadtask(.exe cute (URL);} catch (rejectedexecutionexception e) {log. D (remoteimageapplication. tag, "Download failed") ;}} E LSE {log. I (remoteimageapplication. tag, "loading images from files"); remoteimageapplication. getinstance (). getimagecache (). put (URL, tbmp); this. setimagebitmap (tbmp);} updatecachesize (pathfilename); // check the file size to clear the cache .}} private void updatecachesize (string pathfilename) {// todo auto-generated method stub updatesizecache (pathfilename );} /*** check whether the file directory exceeds the specified cache size ** @ Param filename */private void updatesizeca Che (string pathfilename) {// todo auto-generated method stub mcachesize = preferencemanager. getdefasharsharedpreferences (mcontext ). getint (remotesettings. cache_size, 100); // read the set cache size. The foreground can dynamically set this value if (issdcardenable () {string extstoragedirectory = environment. getexternalstoragedirectory (). tostring (); // get the SD root path string dirpath = extstoragedirectory + "/" + jamendo_dir + "/imagecache"; file dirfil E = new file (dirpath); file [] files = dirfile. listfiles (); long dirsize = 0; For (File file: Files) {dirsize + = file. length () ;}if (dirsize> mcachesize * MB) {audio AchE () ;}}/ *** download image asynchronously ** @ classname: downloadtask * @ author Jiang Tao * @ version 1.0 5:06:21 */class downloadtask extends asynctask <string, void, string> {private string mtaskurl; private bitmap mbmp = NULL; @ override Public void onpreexecute () {// loaddefaultimage (); super. onpreexecute () ;}@ override Public String doinbackground (string... params) {mtaskurl = Params [0]; inputstream stream = NULL; Url imageurl; bitmap BMP = NULL; try {imageurl = new URL (mtaskurl); try {stream = imageurl. openstream (); BMP = bitmapfactory. decodestream (Stream); try {If (BMP! = NULL) {mbmp = BMP; remoteimageapplication. getinstance (). getimagecache (). put (mtaskurl, BMP); log. D (remoteimageapplication. tag, "image cached in application:" + mtaskurl) ;}} catch (nullpointerexception e) {log. W (remoteimageapplication. tag, "Download failed, image is empty:" + mtaskurl) ;}} catch (ioexception e) {log. W (remoteimageapplication. tag, "unable to load this URL:" + mtaskurl);} finally {try {If (stream! = NULL) {stream. close () ;}} catch (ioexception e) {}} catch (malformedurlexception e) {e. printstacktrace ();} return mtaskurl;} @ override public void onpostexecute (string URL) {super. onpostexecute (URL); bitmap BMP = remoteimageapplication. getinstance (). getimagecache (). get (URL); If (BMP = NULL) {log. W (remoteimageapplication. tag, "try to download again:" + URL); remoteimageview. this. setimageurl (URL );} Else {remoteimageview. this. setimagebitmap (BMP); mcurrentlygrabbedurl = URL; savebmptosd (mbmp, URL );}}}; /*** Save the image locally ** @ Param BM * @ Param URL */private void savebmptosd (Bitmap BM, string URL) {If (Bm = NULL) {return;} If (mcachesize = 0) {return;} string filename = converturltofilename (URL); string dir = getdirectory (filename ); file file = new file (DIR + "/" + filename); try {File. Createnewfile (); outputstream outstream = new fileoutputstream (File); BM. compress (bitmap. compressformat. JPEG, 100, outstream); outstream. flush (); outstream. close (); log. I (remoteimageapplication. tag, "image saved to SD card");} catch (filenotfoundexception e) {log. W (remoteimageapplication. tag, "file directory not found");} catch (ioexception e) {log. W (remoteimageapplication. tag, "Operation file error");}/*** name of the group spelling file, with the suffix replaced by dat, to prevent others from using The image manager searches for such images that are useless to them. ** @ Param URL * @ return */private string converturltofilename (string URL) {string filename = URL; filename = filename. replace ("http: //", ""); filename = filename. replace ("/",". "); filename = filename. replace (":",". "); filename = filename. replace ("jpg", "dat"); filename = filename. replace ("PNG", "dat"); Return filename;}/*** return the folder where the cached image is stored ** @ Param filename * @ return * /Private string getdirectory (string filename) {string extstoragedirectory = environment. getexternalstoragedirectory (). tostring (); // obtain the SD root path string dirpath = extstoragedirectory + "/" + jamendo_dir + "/imagecache"; file dirfile = new file (dirpath); If (! Dirfile. exists () {dirfile. mkdirs ();} return dirpath;}/*** clear cache */private void revoke AchE () {If (issdcardenable () {string extstoragedirectory = environment. getexternalstoragedirectory (). tostring (); // obtain the SD root path string dirpath = extstoragedirectory + "/" + jamendo_dir + "/imagecache"; file dir = new file (dirpath ); file [] files = dir. listfiles (); // obtain all files in this directory if (Files = NULL | files. length = 0) {return;} For (File file: Files) {file. delete ();} log. D (remoteimageapplication. tag, "cache cleared:" + dirpath) ;}/ *** determine whether the SD card is available */public static Boolean issdcardenable () {return environment. getexternalstoragestate (). equals (environment. media_mounted );}}

This article from: http://lewisliu.iteye.com/blog/1346820

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.