Use LruCache and DiskLruCache to download images,

Source: Internet
Author: User

Use LruCache and DiskLruCache to download images,

LruCache is a good image caching tool:

The main method is to cache the bitmap of the image in LruCache <String, Bitmap> when sliding the image. After exiting the program, the image is cached in the file and the DiskLruCache mDiskLruCache is used.


Therefore, we must set an image cache address:

public void setImageCache(){    String strPath = null;    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {    File sdFile = Environment.getExternalStorageDirectory();    strPath = sdFile.getAbsolutePath() + "/pic/";    File cacheFile = new File(strPath);        if(!cacheFile.exists()){        cacheFile.mkdir();        }    }    else{    String strCacheDir = this.getCacheDir().getAbsolutePath();    strPath = strCacheDir + "/pic/";    }    setCachePath(strPath);    }private void setCachePath(String strPicCachePath){if(TextUtils.isEmpty(strPicCachePath)){return;}m_strPicCachePath = strPicCachePath;File cacheFile = new File(strPicCachePath);        if(!cacheFile.exists()){        cacheFile.mkdir();        }}public String getCacheBmpPath(String strUrl){if(TextUtils.isEmpty(m_strPicCachePath) || TextUtils.isEmpty(strUrl)){return "";}return m_strPicCachePath + StringUtil.MD5Encode(strUrl) + mFileExName;//".bmp";}

Then write the List adapter:

Private class ListAdapter extends BaseAdapter implements OnScrollListener {protected List <ShopData> items = new ArrayList <ShopData> (); protected static final int priority = 1; private LruCache <String, Bitmap> mMemoryCache; protected HashSet <ImageView> mItemsMissingImages = new HashSet <ImageView> (); protected ImageLoaderHandler mHandler; protected ImageLoader mImageFetcher; public static final int TIMEOUT = 30000; // TIMEOUT time 30 seconds private DiskLruCache mDiskLruCache; public ListAdapter () {super (); mHandler = new ImageLoaderHandler (); int maxMemory = (int) Runtime. getRuntime (). maxMemory (); int mCacheSize = maxMemory/8; // allocate 1/8 4 MmMemoryCache = new LruCache <String, Bitmap> (mCacheSize) to LruCache {// This method must be rewritten, to measure the Bitmap size @ Overrideprotected int sizeOf (String key, Bitmap value) {return value. getRowBytes () * v Alue. getHeight () ;}; try {mDiskLruCache = DiskLruCache. open (new File (m_strPicCachePath), getAppVersion (MainActivityTest. this), 1, 10*1024*1024);} catch (IOException e) {e. printStackTrace () ;}}/*** synchronize cache records to the journal File. */Public void fluchCache () {if (mDiskLruCache! = Null) {try {mDiskLruCache. flush ();} catch (IOException e) {e. printStackTrace () ;}}@ Overridepublic int getCount () {return items. size () ;}@ Overridepublic Object getItem (int position) {return items. get (position) ;}@ Overridepublic long getItemId (int position) {return position ;}@ Overridepublic View getView (int position, View convertView, ViewGroup parent) {ShopDataTag tag = new ShopDataTag (); if (convert View = null) {convertView = mInflater. inflate (R. layout. listitem, null); tag. name = (TextView) convertView. findViewById (R. id. name); tag. shopInfo = (TextView) convertView. findViewById (R.id.info); tag. icon = (ImageView) convertView. findViewById (R. id. image_icon); convertView. setTag (tag);} else {tag = (ShopDataTag) convertView. getTag ();} TextView name = tag. name; TextView info = tag. shopInfo; ImageView image View = tag. icon; ShopData data = items. get (position); name. setText (data. name); info. setText (data.info); imageView. setTag (data. url); setContactPhoto (data. url, imageView); return convertView;} protected void setContactPhoto (String url, ImageView viewToUse) {if (TextUtils. isEmpty (url) {viewToUse. setImageResource (R. drawable. avatar);} else {// check whether bitmapBitmap bitmap = mMemoryCache is available in mMemoryCache. get (url); if (B Itmap! = Null) {viewToUse. setImageBitmap (bitmap);} else {Snapshot snapShot = null; FileDescriptor fileDescriptor = null; FileInputStream fileInputStream = null; try {// because mDiskLruCache uses the key as the file name, therefore, convert the url to keyfinal String key = hashKeyForDisk (url) through md5; snapShot = mDiskLruCache. get (key); // if snapShot is empty, the corresponding file if (snapShot = null) is not found {// download fetchImage (viewToUse) here );} else {fileInputStream = (FileInputStream) snapShot. GetInputStream (0); fileDescriptor = fileInputStream. getFD (); if (fileDescriptor! = Null) {bitmap = BitmapFactory. decodeFileDescriptor (fileDescriptor);} // if the file fails to be parsed as bitmap, download it again if (! TextUtils. isEmpty (url) & bitmap! = Null) {mMemoryCache. put (url, bitmap); viewToUse. setImageBitmap (bitmap);} else {fetchImage (viewToUse) ;}} catch (IOException ex) {ex. printStackTrace ();} finally {if (fileDescriptor = null & fileInputStream! = Null) {try {fileInputStream. close () ;}catch (IOException e) {}}}} private void fetchImage (ImageView viewToUse) {viewToUse. setImageResource (R. drawable. avatar); mItemsMissingImages. add (viewToUse); if (mScrollState! = OnScrollListener. SCROLL_STATE_FLING) {sendFetchImageMessage (viewToUse) ;}} public String <strong> hashKeyForDisk </strong> (String key) {convert the key to the md5 file return StringUtil. MD5Encode (key);} // image downloaderprivate class ImageLoaderHandler extends Handler {@ Overridepublic void handleMessage (Message message) {if (isFinishing () {return;} switch (message. what) {case FETCH_IMAGE_MSG: {final ImageView imageVie W = (ImageView) message. obj; if (imageView = null) {break;} final String url = (String) imageView. getTag (); if (TextUtils. isEmpty (url) {break;} Bitmap map = getBitmapFromMemCache (url); if (map = null) {break;} synchronized (imageView) {final String myUrl = (String) imageView. getTag (); if (TextUtils. equals (url, myUrl) {imageView. setImageBitmap (map); mItemsMissingImages. remove (imageView);} else {}} break ;}} Public void clearImageFecthing () {removeMessages (FETCH_IMAGE_MSG) ;}} private class ImageLoader implements Runnable {String url; private ImageView mImageView; public ImageLoader (String url, ImageView imageView) {this. url = url; this. mImageView = imageView;} public void run () {if (isFinishing () {return;} if (Thread. interrupted () {return;} FileDescriptor fileDescriptor = null; FileInputStream fileInput Stream = null; Snapshot snapShot = null; try {final String key = hashKeyForDisk (url); snapShot = mDiskLruCache. get (key); if (snapShot = null) {// if the corresponding cache is not found, request data from the network and write it to the cache DiskLruCache. editor editor = mDiskLruCache. edit (key); if (editor! = Null) {OutputStream outputStream = editor. newOutputStream (0); boolean flag = downloadImage (url, outputStream); if (flag) {editor. commit ();} else {editor. abort () ;}// after the cache is written, find the cache snapShot = mDiskLruCache corresponding to the key again. get (key) ;}// Delete the corresponding object if (snapShot! = Null) {fileInputStream = (FileInputStream) snapShot. getInputStream (0); fileDescriptor = fileInputStream. getFD () ;}// resolve the cached data to the Bitmap object Bitmap bitmap = null; if (fileDescriptor! = Null) {bitmap = BitmapFactory. decodeFileDescriptor (fileDescriptor);} if (bitmap! = Null) {// Add a Bitmap object to the memory cache. put (url, bitmap) ;}} catch (IOException e) {e. printStackTrace ();} finally {if (fileDescriptor = null & fileInputStream! = Null) {try {fileInputStream. close () ;}catch (IOException e) {}} if (Thread. interrupted () {return;} Message msg = new Message (); msg. what = FETCH_IMAGE_MSG; msg. obj = mImageView; mHandler. sendMessage (msg) ;}} public Bitmap getBitmapFromMemCache (String key) {return mMemoryCache. get (key);} public boolean downloadImage (String strUrl, OutputStream fos) {URL getUrl = null; Bitmap bitmap = null; BufferedOutpu TStream out = null; BufferedInputStream in = null; try {getUrl = new URL (strUrl);} catch (MalformedURLException ex) {Log. e ("HttpUtil", "get MalformedURL", ex); return false;} InputStream input = null; HttpURLConnection conn = null; try {conn = (HttpURLConnection) getUrl. openConnection (); conn. setConnectTimeout (TIMEOUT); conn. setReadTimeout (TIMEOUT); conn. setDoInput (true); conn. connect (); input = conn. getInput Stream (); in = new BufferedInputStream (input, 8*1024); out = new BufferedOutputStream (fos, 8*1024); int B; while (B = in. read ())! =-1) {out. write (B);} return true;} catch (Exception ex) {Log. e ("HttpUtil", "downloadImage", ex);} catch (OutOfMemoryError ex) {ex. printStackTrace ();} finally {try {if (out! = Null) {out. close (); out = null;} if (in! = Null) {in. close (); in = null;} if (conn! = Null) {conn. disconnect (); conn = null ;}} catch (Exception ex) {Log. e ("HttpUtil", "downloadImage finally", ex) ;}return false;} private boolean getResponse (InputStream input, OutputStream OS, byte [] data) throws IOException {if (input = null | OS = null | data = null) {return false;} int I = 0; while (I = input. read (data ))! =-1) {OS. write (data, 0, I); OS. flush ();} OS. flush (); return true;} private void processMissingImageItems (AbsListView view) {for (ImageView iv: Images) {sendFetchImageMessage (iv) ;}} protected void sendFetchImageMessage (ImageView view) {final String url = (String) view. getTag (); if (TextUtils. isEmpty (url) {return;} mImageFetcher = new ImageLoader (url, view); synchronized (MainActivityTest. this) {If (sImageFetchThreadPool = null) {sImageFetchThreadPool = effeccute (mImageFetcher) ;}} public void clearImageFetching () {synchronized (MainActivityTest. this) {if (response! = Null) {sImageFetchThreadPool. shutdownNow (); sImageFetchThreadPool = null ;}} mHandler. clearImageFecthing ();} public void clearMessages () {if (mHandler! = Null) {try {mHandler. removeCallbacksAndMessages (null);} catch (java. lang. throwable th) {} mHandler = null ;}@ Overridepublic void onScrollStateChanged (AbsListView view, int scrollState) {mScrollState = scrollState; if (scrollState = OnScrollListener. topology) {clearImageFetching () ;}else {processMissingImageItems (view) ;}@overridepublic void onScroll (AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {}} private class ShopDataTag {TextView name; TextView shopInfo; ImageView icon ;}

:

Code: http://download.csdn.net/detail/baidu_nod/7777137




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.