ACache【輕量級的開源快取框架】
前言
官方介紹
ASimpleCache 是一個為android制定的 輕量級的 開源快取框架。輕量到只有一個java檔案(由十幾個類精簡而來)。
1、它可以快取什麼東西?
普通的字串、JsonObject、JsonArray、Bitmap、Drawable、序列化的java物件,和 byte資料。
2、它有什麼特色?
特色主要是:
1:輕,輕到只有一個JAVA檔案。
2:可配置,可以配置快取路徑,快取大小,快取數量等。
3:可以設定快取超時時間,快取超時自動失效,並被刪除。
4:支援多程序。
3、它在android中可以用在哪些場景?
1、替換SharePreference當做配置檔案
2、可以快取網路請求資料,比如oschina的android客戶端可以快取http請求的新聞內容,快取時間假設為1個小時,超時後自動失效,讓客戶端重新請求新的資料,減少客戶端流量,同時減少伺服器併發量。
4、如何使用 ASimpleCache? 以下有個小的demo,希望您能喜歡:
快取資料
ACache.get(MainActivity.this).put("username_key", "admin"); ACache.get(MainActivity.this).put("password_key", "123456789", 10);//儲存10秒,如果超過10秒去獲取這個key,將為null ACache.get(MainActivity.this).put("password_key", "123456789", 2 * ACache.TIME_DAY);//儲存兩天,如果超過兩天去獲取這個key,將為null
獲取資料
ACache.get(MainActivity.this).getAsString("username_key");
效果圖
程式碼分析
快取檔案放置在/data/data/app-package-name/cache/路徑下,快取的目錄預設為ACache,快取大小和數量均由ACache中的final變數控制。
存在的一個問題是,在部分機型(比如華為榮耀6)上當使用獵豹清理大師進行垃圾清理的時候會把acache中快取的資料清理掉。
使用步驟
一、專案組織結構圖
注意事項:
1、匯入類檔案後需要change包名以及重新import R檔案路徑
2、Values目錄下的檔案(strings.xml、dimens.xml、colors.xml等),如果專案中存在,則複製裡面的內容,不要整個覆蓋
二、匯入步驟
將Acache複製到專案中
/** * Copyright (c) 2012-2013, Michael Yang 楊福海 (www.yangfuhai.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.why.project.acachedemo.utils; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.PixelFormat; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import org.json.JSONArray; import org.json.JSONObject; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.RandomAccessFile; import java.io.Serializable; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; /** * https://github.com/yangfuhai/ASimpleCache * 快取檔案放置在/data/data/app-package-name/cache/路徑下,快取的目錄預設為ACache,快取大小和數量均由ACache中的final變數控制。 */ public class ACache { /**設定的快取的時間*/ public static final int TIME_HOUR = 60 * 60;//1小時 public static final int TIME_DAY = TIME_HOUR * 24;//1天 /**設定的快取的大小*/ private static final int MAX_SIZE = 1000 * 1000 * 50; // 50 MB private static final int MAX_COUNT = Integer.MAX_VALUE; // 不限制存放資料的數量 /**宣告一個Map,用於存放ACache物件*/ private static Map<String, ACache> mInstanceMap = new HashMap<String, ACache>(); /**快取管理器*/ private ACacheManager mCacheManager; //ACache類的構造方法為private的,所以只能通過get方式獲取例項。 private ACache(File cacheDir, long max_size, int max_count) { //如果cacheDir檔案不存在並且無法新建子目錄,則報錯 if (!cacheDir.exists() && !cacheDir.mkdirs()) { throw new RuntimeException("can't make dirs in " + cacheDir.getAbsolutePath()); } //例項化快取管理器物件 mCacheManager = new ACacheManager(cacheDir, max_size, max_count); } //預設情況下呼叫該方法 public static ACache get(Context ctx) { return get(ctx, "ACache"); } public static ACache get(Context ctx, long max_zise, int max_count) { File f = new File(ctx.getCacheDir(), "ACache"); return get(f, max_zise, max_count); } public static ACache get(Context ctx, String cacheName) { File f = new File(ctx.getCacheDir(), cacheName); return get(f, MAX_SIZE, MAX_COUNT); } public static ACache get(File cacheDir) { return get(cacheDir, MAX_SIZE, MAX_COUNT); } //最終預設呼叫的例項方法 public static ACache get(File cacheDir, long max_zise, int max_count) { //Map中的Key值為cacheDir.getAbsoluteFile() + myPid(),例如:/data/data/com.yangfuhai.asimplecachedemo/cache/ACache_16609 ACache manager = mInstanceMap.get(cacheDir.getAbsoluteFile() + myPid()); if (manager == null) { manager = new ACache(cacheDir, max_zise, max_count); //Log.v("ACache", cacheDir.getAbsolutePath() + myPid()); mInstanceMap.put(cacheDir.getAbsolutePath() + myPid(), manager); } return manager; } private static String myPid() { return "_" + android.os.Process.myPid(); } /** * Provides a means to save a cached file before the data are available. * Since writing about the file is complete, and its close method is called, * its contents will be registered in the cache. Example of use: * * ACache cache = new ACache(this) try { OutputStream stream = * cache.put("myFileName") stream.write("some bytes".getBytes()); // now * update cache! stream.close(); } catch(FileNotFoundException e){ * e.printStackTrace() } */ class xFileOutputStream extends FileOutputStream { File file; public xFileOutputStream(File file) throws FileNotFoundException { super(file); this.file = file; } public void close() throws IOException { super.close(); mCacheManager.put(file); } } // ======================================= // ============ String資料 讀寫 ============== // ======================================= /** * 儲存 String資料 到 快取中 * * @param key * 儲存的key * @param value * 儲存的String資料 */ //在ACache目錄下建立一個檔案,檔名為:File(cacheDir, key.hashCode() + “”)。然後將資料存入檔案 public void put(String key, String value) { File file = mCacheManager.newFile(key); BufferedWriter out = null; try { out = new BufferedWriter(new FileWriter(file), 1024); out.write(value); } catch (IOException e) { e.printStackTrace(); } finally { if (out != null) { try { out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } } mCacheManager.put(file); } } /** * 儲存 String資料 到 快取中一定時間 * * @param key * 儲存的key * @param value * 儲存的String資料 * @param saveTime * 儲存的時間,單位:秒 */ public void put(String key, String value, int saveTime) { put(key, Utils.newStringWithDateInfo(saveTime, value)); } /** * 讀取 String資料 * * @param key * @return String 資料 */ public String getAsString(String key) { File file = mCacheManager.get(key); if (!file.exists()) return null; boolean removeFile = false; BufferedReader in = null; try { in = new BufferedReader(new FileReader(file)); String readString = ""; String currentLine; while ((currentLine = in.readLine()) != null) { readString += currentLine; } if (!Utils.isDue(readString)) { return Utils.clearDateInfo(readString); } else { removeFile = true; return null; } } catch (IOException e) { e.printStackTrace(); return null; } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } if (removeFile) remove(key); } } // ======================================= // ============= JSONObject 資料 讀寫 ============== // ======================================= /** * 儲存 JSONObject資料 到 快取中 * * @param key * 儲存的key * @param value * 儲存的JSON資料 */ public void put(String key, JSONObject value) { put(key, value.toString()); } /** * 儲存 JSONObject資料 到 快取中 * * @param key * 儲存的key * @param value * 儲存的JSONObject資料 * @param saveTime * 儲存的時間,單位:秒 */ public void put(String key, JSONObject value, int saveTime) { put(key, value.toString(), saveTime); } /** * 讀取JSONObject資料 * * @param key * @return JSONObject資料 */ public JSONObject getAsJSONObject(String key) { String JSONString = getAsString(key); if(JSONString != null){ try { JSONObject obj = new JSONObject(JSONString); return obj; } catch (Exception e) { e.printStackTrace(); return null; } }else{ return null; } } // ======================================= // ============ JSONArray 資料 讀寫 ============= // ======================================= /** * 儲存 JSONArray資料 到 快取中 * * @param key * 儲存的key * @param value * 儲存的JSONArray資料 */ public void put(String key, JSONArray value) { put(key, value.toString()); } /** * 儲存 JSONArray資料 到 快取中 * * @param key * 儲存的key * @param value * 儲存的JSONArray資料 * @param saveTime * 儲存的時間,單位:秒 */ public void put(String key, JSONArray value, int saveTime) { put(key, value.toString(), saveTime); } /** * 讀取JSONArray資料 * * @param key * @return JSONArray資料 */ public JSONArray getAsJSONArray(String key) { String JSONString = getAsString(key); try { JSONArray obj = new JSONArray(JSONString); return obj; } catch (Exception e) { e.printStackTrace(); return null; } } // ======================================= // ============== byte 資料 讀寫 ============= // ======================================= /** * 儲存 byte資料 到 快取中 * * @param key * 儲存的key * @param value * 儲存的資料 */ public void put(String key, byte[] value) { File file = mCacheManager.newFile(key); FileOutputStream out = null; try { out = new FileOutputStream(file); out.write(value); } catch (Exception e) { e.printStackTrace(); } finally { if (out != null) { try { out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } } mCacheManager.put(file); } } /** * Cache for a stream * * @param key * the file name. * @return OutputStream stream for writing data. * @throws FileNotFoundException * if the file can not be created. */ public OutputStream put(String key) throws FileNotFoundException { return new xFileOutputStream(mCacheManager.newFile(key)); } /** * * @param key * the file name. * @return (InputStream or null) stream previously saved in cache. * @throws FileNotFoundException * if the file can not be opened */ public InputStream get(String key) throws FileNotFoundException { File file = mCacheManager.get(key); if (!file.exists()) return null; return new FileInputStream(file); } /** * 儲存 byte資料 到 快取中 * * @param key * 儲存的key * @param value * 儲存的資料 * @param saveTime * 儲存的時間,單位:秒 */ public void put(String key, byte[] value, int saveTime) { put(key, Utils.newByteArrayWithDateInfo(saveTime, value)); } /** * 獲取 byte 資料 * * @param key * @return byte 資料 */ public byte[] getAsBinary(String key) { RandomAccessFile RAFile = null; boolean removeFile = false; try { File file = mCacheManager.get(key); if (!file.exists()) return null; RAFile = new RandomAccessFile(file, "r"); byte[] byteArray = new byte[(int) RAFile.length()]; RAFile.read(byteArray); if (!Utils.isDue(byteArray)) { return Utils.clearDateInfo(byteArray); } else { removeFile = true; return null; } } catch (Exception e) { e.printStackTrace(); return null; } finally { if (RAFile != null) { try { RAFile.close(); } catch (IOException e) { e.printStackTrace(); } } if (removeFile) remove(key); } } // ======================================= // ============= 序列化 資料 讀寫 =============== // ======================================= /** * 儲存 Serializable資料 到 快取中 * * @param key * 儲存的key * @param value * 儲存的value */ public void put(String key, Serializable value) { put(key, value, -1); } /** * 儲存 Serializable資料到 快取中 * * @param key * 儲存的key * @param value * 儲存的value * @param saveTime * 儲存的時間,單位:秒 */ public void put(String key, Serializable value, int saveTime) { ByteArrayOutputStream baos = null; ObjectOutputStream oos = null; try { baos = new ByteArrayOutputStream(); oos = new ObjectOutputStream(baos); oos.writeObject(value); byte[] data = baos.toByteArray(); if (saveTime != -1) { put(key, data, saveTime); } else { put(key, data); } } catch (Exception e) { e.printStackTrace(); } finally { try { oos.close(); } catch (IOException e) { } } } /** * 讀取 Serializable資料 * * @param key * @return Serializable 資料 */ public Object getAsObject(String key) { byte[] data = getAsBinary(key); if (data != null) { ByteArrayInputStream bais = null; ObjectInputStream ois = null; try { bais = new ByteArrayInputStream(data); ois = new ObjectInputStream(bais); Object reObject = ois.readObject(); return reObject; } catch (Exception e) { e.printStackTrace(); return null; } finally { try { if (bais != null) bais.close(); } catch (IOException e) { e.printStackTrace(); } try { if (ois != null) ois.close(); } catch (IOException e) { e.printStackTrace(); } } } return null; } // ======================================= // ============== bitmap 資料 讀寫 ============= // ======================================= /** * 儲存 bitmap 到 快取中 * * @param key * 儲存的key * @param value * 儲存的bitmap資料 */ public void put(String key, Bitmap value) { put(key, Utils.Bitmap2Bytes(value)); } /** * 儲存 bitmap 到 快取中 * * @param key * 儲存的key * @param value * 儲存的 bitmap 資料 * @param saveTime * 儲存的時間,單位:秒 */ public void put(String key, Bitmap value, int saveTime) { put(key, Utils.Bitmap2Bytes(value), saveTime); } /** * 讀取 bitmap 資料 * * @param key * @return bitmap 資料 */ public Bitmap getAsBitmap(String key) { if (getAsBinary(key) == null) { return null; } return Utils.Bytes2Bimap(getAsBinary(key)); } // ======================================= // ============= drawable 資料 讀寫 ============= // ======================================= /** * 儲存 drawable 到 快取中 * * @param key * 儲存的key * @param value * 儲存的drawable資料 */ public void put(String key, Drawable value) { put(key, Utils.drawable2Bitmap(value)); } /** * 儲存 drawable 到 快取中 * * @param key * 儲存的key * @param value * 儲存的 drawable 資料 * @param saveTime * 儲存的時間,單位:秒 */ public void put(String key, Drawable value, int saveTime) { put(key, Utils.drawable2Bitmap(value), saveTime); } /** * 讀取 Drawable 資料 * * @param key * @return Drawable 資料 */ public Drawable getAsDrawable(String key) { if (getAsBinary(key) == null) { return null; } return Utils.bitmap2Drawable(Utils.Bytes2Bimap(getAsBinary(key))); } /** * 獲取快取檔案 * * @param key * @return value 快取的檔案 */ public File file(String key) { File f = mCacheManager.newFile(key); if (f.exists()) return f; return null; } /** * 移除某個key * * @param key * @return 是否移除成功 */ public boolean remove(String key) { return mCacheManager.remove(key); } /** * 清除所有資料 */ public void clear() { mCacheManager.clear(); } /** * @title 快取管理器 * @author 楊福海(michael) www.yangfuhai.com * @version 1.0 */ public class ACacheManager { private final AtomicLong cacheSize; private final AtomicInteger cacheCount; private final long sizeLimit; private final int countLimit; private final Map<File, Long> lastUsageDates = Collections.synchronizedMap(new HashMap<File, Long>()); protected File cacheDir; private ACacheManager(File cacheDir, long sizeLimit, int countLimit) { this.cacheDir = cacheDir; this.sizeLimit = sizeLimit; this.countLimit = countLimit; cacheSize = new AtomicLong(); cacheCount = new AtomicInteger(); calculateCacheSizeAndCacheCount(); } /** * 計算 cacheSize和cacheCount */ private void calculateCacheSizeAndCacheCount() { new Thread(new Runnable() { @Override public void run() { int size = 0; int count = 0; File[] cachedFiles = cacheDir.listFiles(); if (cachedFiles != null) { for (File cachedFile : cachedFiles) { size += calculateSize(cachedFile); count += 1; lastUsageDates.put(cachedFile, cachedFile.lastModified()); } cacheSize.set(size); cacheCount.set(count); } } }).start(); } private void put(File file) { int curCacheCount = cacheCount.get(); while (curCacheCount + 1 > countLimit) { long freedSize = removeNext(); cacheSize.addAndGet(-freedSize); curCacheCount = cacheCount.addAndGet(-1); } cacheCount.addAndGet(1); long valueSize = calculateSize(file); long curCacheSize = cacheSize.get(); while (curCacheSize + valueSize > sizeLimit) { long freedSize = removeNext(); curCacheSize = cacheSize.addAndGet(-freedSize); } cacheSize.addAndGet(valueSize); Long currentTime = System.currentTimeMillis(); file.setLastModified(currentTime); lastUsageDates.put(file, currentTime); } private File get(String key) { File file = newFile(key); Long currentTime = System.currentTimeMillis(); file.setLastModified(currentTime); lastUsageDates.put(file, currentTime); return file; } private File newFile(String key) { return new File(cacheDir, key.hashCode() + ""); } private boolean remove(String key) { File image = get(key); return image.delete(); } private void clear() { lastUsageDates.clear(); cacheSize.set(0); File[] files = cacheDir.listFiles(); if (files != null) { for (File f : files) { f.delete(); } } } /** * 移除舊的檔案 * * @return */ private long removeNext() { if (lastUsageDates.isEmpty()) { return 0; } Long oldestUsage = null; File mostLongUsedFile = null; Set<Entry<File, Long>> entries = lastUsageDates.entrySet(); synchronized (lastUsageDates) { for (Entry<File, Long> entry : entries) { if (mostLongUsedFile == null) { mostLongUsedFile = entry.getKey(); oldestUsage = entry.getValue(); } else { Long lastValueUsage = entry.getValue(); if (lastValueUsage < oldestUsage) { oldestUsage = lastValueUsage; mostLongUsedFile = entry.getKey(); } } } } long fileSize = calculateSize(mostLongUsedFile); if (mostLongUsedFile.delete()) { lastUsageDates.remove(mostLongUsedFile); } return fileSize; } private long calculateSize(File file) { return file.length(); } } /** * @title 時間計算工具類 * @author 楊福海(michael) www.yangfuhai.com * @version 1.0 */ private static class Utils { /** * 判斷快取的String資料是否到期 * * @param str * @return true:到期了 false:還沒有到期 */ private static boolean isDue(String str) { return isDue(str.getBytes()); } /** * 判斷快取的byte資料是否到期 * * @param data * @return true:到期了 false:還沒有到期 */ private static boolean isDue(byte[] data) { String[] strs = getDateInfoFromDate(data); if (strs != null && strs.length == 2) { String saveTimeStr = strs[0]; while (saveTimeStr.startsWith("0")) { saveTimeStr = saveTimeStr.substring(1, saveTimeStr.length()); } long saveTime = Long.valueOf(saveTimeStr); long deleteAfter = Long.valueOf(strs[1]); if (System.currentTimeMillis() > saveTime + deleteAfter * 1000) { return true; } } return false; } private static String newStringWithDateInfo(int second, String strInfo) { return createDateInfo(second) + strInfo; } private static byte[] newByteArrayWithDateInfo(int second, byte[] data2) { byte[] data1 = createDateInfo(second).getBytes(); byte[] retdata = new byte[data1.length + data2.length]; System.arraycopy(data1, 0, retdata, 0, data1.length); System.arraycopy(data2, 0, retdata, data1.length, data2.length); return retdata; } private static String clearDateInfo(String strInfo) { if (strInfo != null && hasDateInfo(strInfo.getBytes())) { strInfo = strInfo.substring(strInfo.indexOf(mSeparator) + 1, strInfo.length()); } return strInfo; } private static byte[] clearDateInfo(byte[] data) { if (hasDateInfo(data)) { return copyOfRange(data, indexOf(data, mSeparator) + 1, data.length); } return data; } private static boolean hasDateInfo(byte[] data) { return data != null && data.length > 15 && data[13] == '-' && indexOf(data, mSeparator) > 14; } private static String[] getDateInfoFromDate(byte[] data) { if (hasDateInfo(data)) { String saveDate = new String(copyOfRange(data, 0, 13)); String deleteAfter = new String(copyOfRange(data, 14, indexOf(data, mSeparator))); return new String[] { saveDate, deleteAfter }; } return null; } private static int indexOf(byte[] data, char c) { for (int i = 0; i < data.length; i++) { if (data[i] == c) { return i; } } return -1; } private static byte[] copyOfRange(byte[] original, int from, int to) { int newLength = to - from; if (newLength < 0) throw new IllegalArgumentException(from + " > " + to); byte[] copy = new byte[newLength]; System.arraycopy(original, from, copy, 0, Math.min(original.length - from, newLength)); return copy; } private static final char mSeparator = ' '; private static String createDateInfo(int second) { String currentTime = System.currentTimeMillis() + ""; while (currentTime.length() < 13) { currentTime = "0" + currentTime; } return currentTime + "-" + second + mSeparator; } /* * Bitmap → byte[] */ private static byte[] Bitmap2Bytes(Bitmap bm) { if (bm == null) { return null; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); bm.compress(Bitmap.CompressFormat.PNG, 100, baos); return baos.toByteArray(); } /* * byte[] → Bitmap */ private static Bitmap Bytes2Bimap(byte[] b) { if (b.length == 0) { return null; } return BitmapFactory.decodeByteArray(b, 0, b.length); } /* * Drawable → Bitmap */ private static Bitmap drawable2Bitmap(Drawable drawable) { if (drawable == null) { return null; } // 取 drawable 的長寬 int w = drawable.getIntrinsicWidth(); int h = drawable.getIntrinsicHeight(); // 取 drawable 的顏色格式 Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; // 建立對應 bitmap Bitmap bitmap = Bitmap.createBitmap(w, h, config); // 建立對應 bitmap 的畫布 Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, w, h); // 把 drawable 內容畫到畫布中 drawable.draw(canvas); return bitmap; } /* * Bitmap → Drawable */ @SuppressWarnings("deprecation") private static Drawable bitmap2Drawable(Bitmap bm) { if (bm == null) { return null; } BitmapDrawable bd=new BitmapDrawable(bm); bd.setTargetDensity(bm.getDensity()); return new BitmapDrawable(bm); } } }
將Globals複製到專案中(或者在類似檔案(用於存放全域性變數和公共方法)中新增以下程式碼)
package com.why.project.acachedemo.utils; /** * Created HaiyuKing * Used 全域性變數和公共方法 */ public class Globals { /**==================快取的key值===============================*/ /**使用者名稱*/ public static final String USERNAME_KEY = "username"; }
三、使用方法
package com.why.project.acachedemo; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.why.project.acachedemo.utils.ACache; import com.why.project.acachedemo.utils.Globals; public class MainActivity extends AppCompatActivity { private EditText mUsernameEdt; private Button mLoginBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initViews(); initDatas(); initEvents(); } //初始化控制元件 private void initViews(){ mUsernameEdt = (EditText) findViewById(R.id.edt_username); mLoginBtn = (Button) findViewById(R.id.btn_login); } //初始化資料 private void initDatas(){ //判斷是否快取了使用者名稱,如果是的話,讀取快取的使用者名稱並填充到輸入框中 initNamePwdFromCache(); } //初始化事件 private void initEvents(){ mLoginBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String userName = mUsernameEdt.getText().toString(); //快取使用者名稱 ACache.get(MainActivity.this).put(Globals.USERNAME_KEY,userName); Toast.makeText(MainActivity.this,"已快取使用者名稱:"+userName,Toast.LENGTH_SHORT).show(); } }); } /** * 從快取中查詢使用者名稱是否儲存,並載入使用者名稱 * */ private void initNamePwdFromCache() { //有快取檔案 String userNameCache = ACache.get(this).getAsString(Globals.USERNAME_KEY); if (userNameCache != null) { mUsernameEdt.setText(userNameCache); Toast.makeText(MainActivity.this,"已載入快取的使用者名稱:"+userNameCache,Toast.LENGTH_SHORT).show(); } } }
混淆配置
無
參考資料
【Android開源專案分析】android輕量級開源快取框架——ASimpleCache(ACache)原始碼分析
http://blog.csdn.net/zhoubin1992/article/details/46379055
ASimpleCache框架原始碼連結
https://github.com/yangfuhai/ASimpleCache
ASimpleCache開源庫使用分析
http://blog.csdn.net/yanbober/article/details/45306851