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.
-
Second-level 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 second level 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.
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:
-
Creating 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
-
Setting up cached 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 of cached data in seconds
- 5
Fetching data from the cache
Provides a range of getasxxx () methods.
Call different methods to fetch data according to the different data stored
-