Android local cache DiskLruCache complete detailed learning example, disklrucache
MainActivity is as follows:
Package cc. vv; import java. io. file; import java. io. inputStream; import java. io. outputStream; import libcore. io. diskLruCache; import libcore. io. utils; import android. OS. bundle; import android. OS. handler; import android. OS. message; import android. widget. imageView; import android. app. activity; import android. content. context; import android. graphics. bitmap; import android. graphics. bitmapFactory;/*** Demo Description: * Disk LruCache learning example ** DiskLruCache is used for local cache. * For example, if a network image is loaded when the Network is available, the image can still be displayed when the network is unavailable. * The principle is to save the image to the local device. When the network is unavailable, the image is loaded from the local device. * Perform the following steps to simulate the process: * 1. Download an image from the network and save it to DiskLruCache * 2. Obtain the cached image from DiskLruCache and display the following learning notes: * 1 the local cache file path of DiskLruCache is: */sdcard/Android/data/<application package>/cache * when the application is uninstalled, the file will also be deleted * 2 common news apps practices. click a news item from the news list (ListView) To Go To The details page. * images and text are generally displayed on the detailed screen. in this case, the image and text can be saved in different cache folders with the same key. * When a network disconnection occurs, you can retrieve the corresponding image and text based on the key. * 3 In the example, the related APIs of DiskLruCache are used. this section briefly sorts out other important APIs: * 3.1 remove (String key) deletes a cached object. * 3.2 size () to get the total cache size in the cache path. this is common. many apps are prompted about the current cache. * 3.3 flush () synchronizes the operation records in the memory to the log file (that is, the journal File). * This method is generally called in onPause () of the Activity. * 3.4 close () close DiskLruCache. this method corresponds to the open method. * This method is generally called in onDestory () of the Activity. * 3.5 delete () deletes all cached data. * ** learning resources: * http://blog.csdn.net/guolin_blog/article/details/28863651 * Thank you very much */public class MainActivity extends Activity {private ImageView mImageView; pr Ivate DiskLruCache mDiskLruCache; private Context mContext; // The Maximum Cache value for images in DiskLruCache. private int maxSize = 20*1024*1024; private String mImagePath = "http://www.baidu.com/img/bdlogo.png"; private Handler mHandler; private final int FINISH = 9527; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); init ();} private void init () {try {MHandler = new Handler () {@ Overridepublic void handleMessage (Message msg) {super. handleMessage (msg); if (msg. what = FINISH) {getDataFromDiskLruCache () ;}}; mContext = this; mImageView = (ImageView) findViewById (R. id. imageView); initDiskLruCache ();} catch (Exception e) {// TODO: handle exception}/*** initialize DiskLruCache */private void initDiskLruCache () {try {File cacheDir = Utils. getDiskLruCacheDir (mContext, "Bitmap"); if (! CacheDir. exists () {cacheDir. mkdirs ();} int versionCode = Utils. getAppVersionCode (mContext); mDiskLruCache = DiskLruCache. open (cacheDir, versionCode, 1, maxSize); saveDataToDiskLruCache ();} catch (Exception e) {// TODO: handle exception} // write data to DiskLruCacheprivate void saveDataToDiskLruCache () {new Thread (new Runnable () {@ Overridepublic void run () {try {// Step 1: Obtain the unique key value of the image to be cached. string key = Utils. getStri NgByMD5 (mImagePath); // Step 2: Obtain the EditorDiskLruCache. Editor editor = mDiskLruCache. edit (key); if (editor! = Null) {// Step 3: Obtain OutputStreamOutputStream outputStream = Editor from the editor. newOutputStream (0); // Step 4: Download the network image and save it to the DiskLruCache image cache. boolean isSuccessfull = Utils. getBitmapFromNetWorkAndSaveToDiskLruCache (mImagePath, outputStream); if (isSuccessfull) {editor. commit (); mHandler. sendEmptyMessage (FINISH);} else {editor. abort ();} mDiskLruCache. flush () ;}} catch (Exception e ){}}}). start ();} // read private void from DiskLruCache GetDataFromDiskLruCache () {try {// Step 1: Obtain the unique key value of the cached image. string key = Utils. getStringByMD5 (mImagePath); // Step 2: obtain the corresponding snapshotDiskLruCache based on the key. snapshot snapshot = mDiskLruCache. get (key); if (snapshot! = Null) {// Step 3: Obtain InputStreamInputStream inputStream = snapshot from snapshot. getInputStream (0); Bitmap bitmap = BitmapFactory. decodeStream (inputStream); mImageView. setImageBitmap (bitmap) ;}} catch (Exception e ){}}}
Utils is as follows:
Package libcore. io; import java. io. bufferedInputStream; import java. io. bufferedOutputStream; import java. io. file; import java. io. inputStream; import java. io. outputStream; import java.net. httpURLConnection; import java.net. URL; import java. security. messageDigest; import java. security. noSuchAlgorithmException; import org. apache. http. httpStatus; import android. content. context; import android. content. pm. packageInf O; import android. content. pm. packageManager; import android. content. pm. packageManager. nameNotFoundException; import android. OS. environment; public class Utils {/*** get the cache folder of DiskLruCache * Note that the second parameter dataType * DiskLruCache uses a unique value of the String type to distinguish different types of data. * Such as bitmap and object. images are cached in the bitmap folder. ** cache data storage location: */sdcard/Android/data/<application package>/cache * If the SD card does not exist, the cache storage location is: */data/<application p Ackage>/cache **/public static File getDiskLruCacheDir (Context context, String dataType) {String dirPath; File cacheFile = null; if (Environment. MEDIA_MOUNTED.equals (Environment. getExternalStorageState () |! Environment. isExternalStorageRemovable () {dirPath = context. getExternalCacheDir (). getPath ();} else {dirPath = context. getCacheDir (). getPath ();} cacheFile = new File (dirPath + File. separator + dataType); return cacheFile;}/*** get the current APP version * @ param context * @ return */public static int getAppVersionCode (Context context) {int versionCode = 1; try {String packageName = context. getPackageName (); PackageManager packageMan Ager = context. getPackageManager (); PackageInfo packageInfo = packageManager. getPackageInfo (packageName, 0); versionCode = packageInfo. versionCode;} catch (NameNotFoundException e) {e. printStackTrace ();} return versionCode;}/*** encode the string with MD5. * For example, in the example, encode the url in MD5 mode */public static String getStringByMD5 (String string) {String md5String = null; try {// Create MD5 HashMessageDigest messageDigest = MessageDigest. g EtInstance ("MD5"); messageDigest. update (string. getBytes (); byte messageDigestByteArray [] = messageDigest. digest (); if (messageDigestByteArray = null | messageDigestByteArray. length = 0) {return md5String;} // Create hexadecimal StringStringBuffer hexadecimalStringBuffer = new StringBuffer (); int length = messageDigestByteArray. length; for (int I = 0; I <length; I ++) {hexadecimalStringBuffer. append (Integer. toHexString (0xFF & messageDigestByteArray [I]);} md5String = hexadecimalStringBuffer. toString (); return md5String;} catch (NoSuchAlgorithmException e) {e. printStackTrace ();} return md5String;}/*** get the image from the network and save it to the cache in the SD card */public static boolean getBitmapFromNetWorkAndSaveToDiskLruCache (String imageUrl, OutputStream outputStream) {boolean isSuccessfull = false; URL url = null; HttpURLConnection httpURLCon Nection = null; BufferedOutputStream bufferedOutputStream = null; InputStream inputStream = null; BufferedInputStream bufferedInputStream = null; try {url = new URL (imageUrl); httpURLConnection = (HttpURLConnection) url. openConnection (); httpURLConnection. setConnectTimeout (5*1000); httpURLConnection. setReadTimeout (10*1000); httpURLConnection. setDoInput (true); httpURLConnection. setDoOutput (true); if (httpURLConnection. g EtResponseCode () = HttpStatus. SC _ OK) {bufferedOutputStream = new BufferedOutputStream (outputStream); inputStream = httpURLConnection. getInputStream (); bufferedInputStream = new BufferedInputStream (inputStream); int len = 0; byte [] buffer = new byte [1024]; while (len = bufferedInputStream. read (buffer ))! =-1) {bufferedOutputStream. write (buffer, 0, len); bufferedOutputStream. flush ();} isSuccessfull = true;} else {isSuccessfull = false; System. out. println ("image request failed") ;}} catch (Exception e) {isSuccessfull = false; System. out. println ("e =" + e. toString ();} finally {try {if (bufferedOutputStream! = Null) {bufferedOutputStream. close () ;}if (inputStream! = Null) {inputStream. close ();} if (bufferedInputStream! = Null) {bufferedInputStream. close () ;}if (httpURLConnection! = Null) {httpURLConnection. disconnect () ;}} catch (Exception e) {System. out. println ("e =" + e. toString () ;}return isSuccessfull ;}}
Main. xml is as follows:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <ImageView android:id="@+id/imageView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" /></RelativeLayout>