Frame Address
Https://github.com/yangfuhai/ASimpleCache This framework author is the famous afinal author
Official profile:
Asimplecache is a lightweight, open-source caching framework developed for Android. Lightweight to only one Java file (reduced by more than 10 classes).
(One problem is that the author's automatic invalidation, in fact, when the data is obtained to determine whether the cached data expires, if expired, delete the data cache, return null.) Of course, if the real automatic deletion, you should only open the service, and constantly determine whether it expires to delete it, it is not necessary )
--------------------------------------------------------------------------------
1. What can it cache?
Ordinary strings, Jsonobject, Jsonarray, Bitmap, drawable, serialized Java objects, and byte data.
2. What is the characteristic of it?
The main features are:
1: Light, light to only one Java file.
2: Configurable, can configure cache path, cache size, cache number, etc.
3: The cache timeout can be set, the cache time-out expires automatically, and is deleted.
4: Multi-process support.
3. What are the scenarios it can use in Android?
1. Replace Sharepreference as configuration file
2, can cache the network request data, for example Oschina's Android client can cache the HTTP request news content, the cache time assumes 1 hours, after the timeout expires automatically, lets the client re-request new data, reduces the client traffic, simultaneously reduces the server concurrency.
3, you say ...
4, how to use Asimplecache?
Here is a small demo, I hope you can enjoy:
Acache Mcache = Acache.get (this);
Mcache.put ("Test_key1", "Test value");
Mcache.put ("Test_key2", "Test Value", 10);//Save 10 seconds, if more than 10 seconds to get this key, will be null
Mcache.put ("Test_key3", "Test Value", 2 * acache.time_day);//Save two days, if more than two days to get this key, will be null
Get Data
Acache Mcache = Acache.get (this);
String value = mcache.getasstring ("Test_key1");
For more examples, see demo
About the author Michael
A dick wire programmer, like open source.
Personal blog:http://www.yangfuhai.com
QQ Group: 192341294 (full) 246710918 (not full)
The main analysis of the Acache in a series of favorite in a class bar (for example, string storage)
First, start by creating a cache
Get (Context ctx, String cachename) method new Cache Directory
get (File cachedir, long max_zise, int max_count) method to create a new cache instance, save the instance Map,key to the cache directory plus the process ID
opened per app
public static Acache Get (Context ctx) {return get (CTX, "Acache");} public static Acache Get (Context ctx, String cachename) {//New cache directory///data/data/com.yangfuhai.asimplecachedemo/cache/ Acachefile 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 (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 (File cachedir, long max_zise, int max_count) {///data/data/com.yangfuhai.asimplecachedemo/ Cache/acacheacache manager = Minstancemap.get (cachedir.getabsolutefile () + mypid ()); if (manager = = null) {manager = new AC Ache (Cachedir, max_zise, max_count);//{/data/data/com.yangfuhai.asimplecachedemo/cache/[email protected]}// {/data/data/com.yangfuhai.asimplecachedemo/cache/[email protected]}minstancemap.put ( Cachedir.getabsolutepath () + mypid (), manager);} ReturnManager;} private static String Mypid () {return ' _ ' + Android.os.Process.myPid ();} Private Acache (File Cachedir, long max_size, int max_count) {if (!cachedir.exists () &&!cachedir.mkdirs ()) {throw New RuntimeException ("Can ' t make dirs in" + Cachedir.getabsolutepath ());} Mcache = new Acachemanager (Cachedir, max_size, max_count);}
Second, deposit data
Put (string key, String value) method writes data to a file
The Mcache.put (file) method in the put (string key, String value) method makes the following settings
After the file is placed in the program cache, the total number of statistics cache, the file is stored in the file map (value is the last modification time of the file, easy to destroy according to the set time of destruction)
Cache does not exceed the limit, increase the total amount of the cache, the value of the total
Cache exceeds the limit, the total number of buffers is reduced
Find the oldest file size using the Removenext method
public void Put (string key, String value) {File File = Mcache.newfile (key); BufferedWriter out = null;try {out = new BufferedWriter (new FileWriter (file), 1024x768); Out.write (value);} catch (IOException e) {e.printstacktrace ();} finally {if (out! = null) {try {out.flush (); Out.close ();} catch (IOException e) {e.printstacktr Ace ();}} Mcache.put (file);}}
After the file is placed in the program cache, the total number of statistics cache, the file is stored in the file map (value value is the last modification time of the file, easy to destroy according to the destruction time of the set)//cache does not exceed the limit, increase the total amount of cache, the total number//cache exceeds the limit, reduce the total cache Number of total values//the size of the oldest file is found by the Removenext method 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);}
/** * Remove the old file (bubbling, find the file with the last modified time) * * @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.getV Alue ();} 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;}
Third, get the data
The getasstring (String key) method reads data from the cache file, in which the Utils.isdue (readString) method is used to determine whether the data is out of date and whether to delete
public string getasstring (string key) {///data/data/com.yangfuhai.asimplecachedemo/cache/acache/1727748931file file = Mcache.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);}}
/** * determine if the cached string data is Period * * @param str * @return true: Expired false: */private static Boolean isdue (String str) {return isdue (Str.getbytes ()) not yet expired; }/** * Determines whether the cached byte data expires (expires: The current time is greater than the save time plus the saved lifetime) * * @param data * @return true: Expired false: Not yet expired */private static Boolean I Sdue (byte[] data) {string[] STRs = getdateinfofromdate (data); if (STRs! = null && strs.length = = 2) {String Savetim Estr = 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 * +) {return true;}} return false;}
Data has no lifetime set private static Boolean Hasdateinfo (byte[] data) {return data! = NULL && data.length > && DATA[13] = = '-' && indexOf (data, Mseparator) >;} Savedate file save time in milliseconds, Deleteafter file retention time after milliseconds private static string[] Getdateinfofromdate (byte[] data) {if ( Hasdateinfo (data) {string savedate = new String (copyofrange (data, 0, 13)); String deleteafter = new String (Copyofrange (data,, indexOf (data, mseparator))); return new string[] {savedate, deleteaf ter};} return null;}
Demo with annotations http://download.csdn.net/detail/superjunjin/8605307
Android Lightweight cache Framework Asimplecache analysis