caching mechanism and implementation in Android

Source: Internet
Author: User

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 classNewslistactivityextendsActivity {PrivateList<news>list; PrivateListView ListView; PrivateLoadimageadapter adapter;//Adapter  Private Acache acache;//Cache framework@Overrideprotected voidonCreate (Bundle savedinstancestate) {//TODO auto-generated Method Stub    Super. OnCreate (savedinstancestate); Super. Setcontentview (r.layout.load_img_listview_activity); Acache =acache.get (this);//Create Acache componentInitview ();//Initialize the interface, the code is not posted} Public voidLoadData () { String cachedata =acache.getasstring ("newslist");//Fetch data from cache   if(cachedata!=NULL){//If there is a cache, you do not have access to the networkList<news> Newslist=gson.fromjson (CacheData,NewTypetoken<list<news>> () {}.gettype ());//Convert JSON to listList.addall (newslist);      Adapter.notifydatasetchanged (); return; }   NewThread (NewRunnable () {@Override Public voidrun () {//TODO auto-generated Method StubSystemclock.sleep (2000);//Analog Network time consumingString json=request ();//simulate getting JSON data from the network       acache.put ("Newslist", JSON, 60*60*1);//data is cached and the effective time is set to 1 hoursList<news> Newslist=gson.fromjson (JSON,NewTypetoken<list<news>>() {}.gettype ());       List.addall (newslist); Handler.sendemptymessage (1);    }}). Start ();} /*** Analog Network request method *@returnJSON data*/PrivateString request () {News News=NULL;  for(inti=0;i<10;i++) {News=NewNews ();       News.setid (i); News.setimgurl ("Course/img/face_" +i+ ". png"); News.settitle ("News Headlines" +i); News.setsummary ("Test" +i);   List.add (news); } Gson Gson=NewGson (); returnGson.tojson (list); }PrivateHandler handler=NewHandler () @Override Public voidhandlemessage (Message msg) {//TODO auto-generated Method Stub       Switch(msg.what) { Case1: 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)

max_size: Set the limit cache size by default to 50M

Max_count: Sets the number of cached data, which is not limited 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

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.