Android Development is essentially the mobile phone and the internet in the communication between the Web server, it is necessary to obtain data from the service side, and repeated over the network to obtain data is more time-consuming, especially when more access, will greatly affect performance, The two-level cache is available in Android to reduce frequent network operations, reduce traffic, and improve performance.
| Secondary caching working mechanism |
The so-called two-level cache is not really complex, when the Android side need to obtain data, such as acquiring images in the network, we first look up from memory (key search), memory is not in the disk file or SQLite to find, if not on the disk to get through the network, when the data from the network, Cache to memory (first-level cache) in Key-value, and cache to file or SQLite (level two cache). Note: Memory caches can cause heap memory leaks, and all first-level caches usually have to tightly control the size of the cache, generally controlling 1/4 of the system's memory.
Understanding the level two cache you might have a problem. The data in the network is changed, once the data is put into the cache, and then the data is obtained from the cache, so it does not reflect the changes in the data? When we cache the data, we set a valid time, say 30 minutes, if the data expires and frees up space, then re-request the data on the network. Some children's shoes to ask in 30 minutes to do? Well, I didn't do it, only the pull-down refresh, actually it's not a problem.
| Implementation of the 二、二级 cache |
How to achieve level two cache, there are many technical solutions, here we use the Asimplecache framework to show you, by name you can see it is very easy to achieve.
1, Acache introduction
Asimplecache is a lightweight, open-source cache framework that is actually a Java class called Acache. It has been used in commercial projects and works well.
: Https://github.com/yangfuhai/ASimpleCache
2, Acache use
Let's start with a case to implement the data cache, and then summarize the main methods
The main code for writing newslistactivity is as follows:
public class Newslistactivity extends Activity {private list<news> List; Private ListView ListView; Private Loadimageadapter adapter;//AdapterPrivate Acache acache;//Cache framework@Override protected void OnCreate (Bundle savedinstancestate) {//TODO auto-generated method stub super.oncreate (SA Vedinstancestate); Super.setcontentview (r.layout.load_img_listview_activity);Acache=acache.get (this);//Create Acache componentInitview ();//Initialize the interface, the code is not affixed with}public void LoadData () {String CacheData=acache.getasstring ("newslist");//Fetch data from cacheif (cachedata!=null) {//If there is a cache, you do not have access to the network list<news> Newslist=gson.fromjson (cachedata, New typetoken<list< News>> () {}.gettype ());//convert JSON to list List.addall (newslist); Adapter.notifydatasetchanged (); Return } New Thread (new Runnable () {@Override public void run () {//TODO auto-generated method Stub syste Mclock.sleep (2000);//analog Network time consuming String json=request ();//simulate getting JSON data from the networkacache.put ("Newslist", JSON, 60*60*1);//data is cached and the effective time is set to 1 hoursList<news> Newslist=gson.fromjson (JSON, new typetoken<list<news>> () {}.gettype ()); List.addall (newslist); Handler.sendemptymessage (1); }}). Start ();} /** * Analog Network Request method * @return JSON data */private String request () {News news=null; for (int i=0;i<10;i++) {news=new News (); News.setid (i); News.setimgurl ("Course/img/face_" +i+ ". png"); News.settitle ("News headlines" +i); News.setsummary ("test" +i); List.add (news); } Gson gson=new Gson (); return Gson.tojson (list); }private Handler handler=new Handler () @Override public void Handlemessage (Message msg) {//TODO auto-generated Method stub switch (msg.what) {case 1:notify_layout.setvisibility (view.gone); Adapter.notifydatasetchanged (); Break } }}
The red part is the code that Asimplecache implements the cached data, let's say the main code
1. Create Acache Components
Acache Acache=acache.get (context)
Or
Acache Acache=acache.get (Context,max_size,max_count)
Parameter description:
Max_size: Set limit cache size, default is 50M
Max_count: Set the number of cached data, no Limit by default
2. Set Cache data
Acache.put (Key,data,time) or acache.put (Key,data)
Storing data in a level cache (memory map) and level two cache (file) at the same time
Parameter description:
Key: Sets a unique identifier for the cached data, based on key when fetching data
Data: The data type to be deposited, Acache supported:
There are string, serializable objects, byte arrays, drawable, and so on.
Time: Set the validity period of the cached data in seconds
3. Fetching data from the cache
Provides a range of getasxxx () methods,
Call different methods to fetch data according to the different data stored
caching mechanism and implementation in Android