Cache mechanism and implementation in Android, and android Cache

Source: Internet
Author: User
Tags addall

Cache mechanism and implementation in Android, and android Cache

Android development is essentially a communication between mobile phones and web servers on the Internet. Therefore, it is necessary to obtain data from the server. It is time-consuming to obtain data through the network repeatedly, especially when there are many accesses, performance is greatly affected. In Android, secondary caching can be used to reduce frequent network operations, reduce traffic, and improve performance.

I. Secondary Cache Mechanism

The so-called level-2 cache is actually not complicated. When the Android end needs to obtain data, such as retrieving images on the network, we first look for the data from the memory (by pressing the key ), if no data exists in the memory, it can be searched from the disk file or sqlite. If no data exists in the disk, it can be obtained through the network. When data from the network is obtained, the key-value pair is used to cache the data to the memory (level-1 cache) and to files or sqlite (level-2 cache ). Note: The memory cache may cause heap memory leakage. The cache size must be strictly controlled for all level-1 caches, typically at 1/4 of the system memory.

I understand that there may be a problem in the second-level cache. The data in the network is changed. Once the data is put into the cache, the data is obtained from the cache. Isn't it unable to reflect the data changes? We set a valid time when caching data, for example, 30 minutes. If the time exceeds this time, the data becomes invalid and the space is released, and then the data in the network is requested again. Some children's shoes ask what to do in 30 minutes? Well, I didn't do it either. I only refresh the drop-down list. In fact, this is not a problem.

II. Implementation of level-2 Cache

There are many technical solutions for how to implement level-2 Cache. Here we use the ASimpleCache framework to show you how to implement it easily.

1. ACache Introduction

ASimpleCache is a lightweight open source cache framework, which is actually a java class called ACache. It has been used in commercial projects and has a good running effect.

: Https://github.com/yangfuhai/ASimpleCache

2. Use ACache

We will first make a case for implementing data caching, 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 (savedInstanceState); super. setContentView (R. layout. load_img_listview_activity );Acache= ACache. get (this); // create an ACache componentInitView (); // initialization interface, code not pasted} public void loadData (){String cacheData= Acache. getAsString ("newsList"); // obtain data from the cacheIf (cacheData! = Null) {// If the cache exists, the Network List is not accessed. <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 SystemClock. sleep (2000); // simulate network time consumption String json = request (); // simulate obtaining json data from the networkAcache. put ("newslist", json, 60*60*1); // Save the data to the cache. The validity period is set to 1 hour.List <News> newsList = gson. fromJson (json, new TypeToken <List <News> (){}. getType (); list. addAll (newsList); handler. sendEmptyMessage (1 );}}). start ();}/*** simulate the 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 title" + 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: policy_layout.setvisibility (View. GONE); adapter. notifyDataSetChanged (); break ;}}}

The red part is the code for implementing the cache data of ASimpleCache. The main code is as follows:

1. Create ACache Components

ACache acache = ACache. get (context)

Or

ACache acache = ACache. get (context, max_size, max_count)

Parameter description:

Max_size: sets the maximum cache size. The default value is 50 MB.

Max_count: sets the number of cached data, which is unlimited by default.

2. Set cache data

Acache. put (key, data, time) or acache. put (key, data)

Store data in both the first-level cache (memory Map) and second-level cache (files ).

Parameter description:

Key: Set a unique identifier for the data stored in the cache. The unique identifier is obtained based on the key when the data is retrieved.

Data: The Data to be stored. Data Types supported by acache:


Including String, serializable object, byte array, Drawable, etc.
Time: set the effective Time of the cached data, in seconds.
3. Fetch data from the cache

Provides a series of getAsXXX () methods,

 

You can call different methods to retrieve data based on different stored data.

 

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.