Android Learning Series (27)-App Cache Management

Source: Internet
Author: User

For large or small applications, flexible caching not only greatly reduces the pressure on servers, but also facilitates users with faster user experience.
Android apk can be said to be a small application, 99% of which do not need to be updated in real time, and is criticized for mobile network speeds like snails. It can interact less with server data, in this way, the user experience is better, which is one of the reasons why we sometimes use json to transmit data without webview.
The use of cache can further reduce the pressure on Data Interaction. Here, we will briefly list the applicable environment of Cache Management:
1. applications that provide Network Services
2. Data Update does not need to be updated in real time, but the cache mechanism can be used even if the delay is 3-5 minutes.
3. the cache expiration time is acceptable (it will not affect the image of the product due to the poor update of some data due to the benefits of the cache)
Benefits:
1. The server pressure is greatly reduced
2. The client's response speed is greatly improved (user experience)
3. Client Data Loading errors are greatly reduced, greatly improving the expected stability (user experience)
4. To a certain extent, it can support offline browsing (or provide technical support for offline browsing)

I. Cache Management Methods
Here, the principle of Cache Management is very simple: through the time settings to determine whether to read the cache or re-download.
There will be some detailed processing, which will be detailed later.
Based on this principle, the two common cache management methods that I have seen are database and file.

Ii. Database Cache Management
After downloading the data file, store the file-related information such as url, path, download time, and expiration time in the database, during the next download, the local file is first queried from the database based on the url. If the current time does not expire, the local file is read Based on the path to achieve the cache effect.
From the implementation, we can see that this method can flexibly store the attributes of files, which provides great scalability and support for other functions;
You need to create a database from the operation, and query the database each time. If the database needs to be updated after expiration, you also need to delete the database data when clearing the cache, which is a little troublesome, improper database operations are prone to a series of performance issues, ANR problems, so you should be cautious when implementing them. For specific operations, it is just a matter of adding a tool class or method.
Another problem is that the cache database is stored in the/data/<package>/databases/directory, which occupies the memory space. If the cache is accumulated, it is easy to waste memory, cache needs to be cleared in a timely manner.
Of course, I have not found any problems in some practical applications.
This article focuses on the second method. The implementation of the first method passes through.

Iii. File Cache Management
In this way, use the File. lastModified () method to get the last modification time of the File, and determine whether the File expires with the current time to achieve the cache effect.
This attribute can only be used for implementation, without providing technical support for other functions.
The operation is simple. Just compare the time. It is not easy to solve other problems, and the cost is low.

IV,Two aspects of File Cache Management
1. Different types of files have different cache times.
In general, the cache time for unchanged files is permanent, and the cache time for changing files is the maximum tolerable duration.
To put it bluntly, the content of the image file remains unchanged until it is cleared. We can always read the cache.
The configuration file content may be updated and an acceptable cache time needs to be set.
2. the cache time standards are different in different environments.
In a non-network environment, we can only read cached files, even if the cache has expired.
In a Wi-Fi network, the cache time can be set to a little shorter. First, the network speed is fast, but the traffic is not money.
In a mobile data traffic environment, the cache time can be set to a little longer to save traffic, which means saving money and better user experience.
For example, I recently set the cache time for an application in wifi environment to 5 minutes, and the cache time for mobile data traffic to 1 hour.
This time is set according to your actual situation: data update frequency, data importance, and so on.

5. When to refresh
On the one hand, developers want to read the cache as much as possible. On the one hand, users want to refresh in real time, but the faster the response speed, the better the traffic consumption. This is a contradiction.
I don't know when to refresh it. Here I provide two suggestions:
1. the maximum length of data remains unchanged, which has no significant impact on applications.
For example, if your data is updated for one day, the cache time is set to 4 ~ 8 hours is more appropriate. He will always see updates one day. If you think you are an information application, reduce it by 2 ~ If you think the data is important or popular for 4 hours, users will often play and reduce it ~ 2 hours, and so on.
For the sake of insurance, you may need to reduce it for no reason.
2. the refresh button is provided.
The insurance mentioned above is not necessarily safe. The safest way is to provide a refresh button on the relevant interface to cache and provide a re-access opportunity for loading failure, with this refresh button, our hearts are truly put down.

Vi. Implementation of the File Cache Method
For the configuration file cache, I created a new ConfigCache class:

Import java. io. file; import java. io. IOException; import android. util. log; import com. tianxia. app. floworld. appApplication; import com. tianxia. app. floworld. utils. fileUtils; import com. tianxia. app. floworld. utils. networkUtils; public class ConfigCache {private static final String TAG = ConfigCache. class. getName (); public static final int CONFIG_CACHE_MOBILE_TIMEOUT = 3600000; // 1 hour public static final in T CONFIG_CACHE_WIFI_TIMEOUT = 300000; // 5 minute public static String getUrlCache (String url) {if (url = null) {return null;} String result = null; file file = new File (AppApplication. mSdcardDataDir + "/" + getCacheDecodeString (url); if (file. exists () & file. isFile () {long expiredTime = System. currentTimeMillis ()-file. lastModified (); Log. d (TAG, file. getAbsolutePath () + "expiredTime:" + ExpiredTime/60000 + "min"); // 1. in case the system time is incorrect (the time is turn back long ago) // 2. when the network is invalid, you can only read the cache if (AppApplication. mNetWorkState! = NetworkUtils. NETWORN_NONE & expiredTime <0) {return null;} if (AppApplication. mNetWorkState = NetworkUtils. NETWORN_WIFI & expiredTime> CONFIG_CACHE_WIFI_TIMEOUT) {return null;} else if (AppApplication. mNetWorkState = NetworkUtils. NETWORN_MOBILE & expiredTime> CONFIG_CACHE_MOBILE_TIMEOUT) {return null;} try {result = FileUtils. readTextFile (file);} catch (IOException e) {e. printStac KTrace () ;}} return result;} public static void setUrlCache (String data, String url) {File file = new File (AppApplication. mSdcardDataDir + "/" + getCacheDecodeString (url); try {// create the cached data to the disk, that is, create the file FileUtils. writeTextFile (file, data);} catch (IOException e) {Log. d (TAG, "write" + file. getAbsolutePath () + "data failed! "); E. printStackTrace () ;}} public static String getCacheDecodeString (String url) {// 1. handle special characters // 2. remove the messy view of the file browser caused by the suffix (especially the image needs to be processed like this, otherwise some mobile phones open the image library, all of which are our cached images) if (url! = Null) {return url. replaceAll ("[.:/, %? & =] "," + "). ReplaceAll (" [+] + "," + ");} return null ;}}

In terms of implementation, we have fully considered several details. The comments have been described and will not be repeated.
The call method is as follows:

Void getConfig () {// first try to read the cache String cacheConfigString = ConfigCache. getUrlCache (CONFIG_URL); // determine whether to read the cache or re-read if (cacheConfigString! = Null) {showConfig (cacheConfigString);} else {// If the cache result is empty, it indicates that the reason for re-loading // The cache to be empty may be 1. no cache; 2. cache expiration; 3. an error occurred while reading the cache. AsyncHttpClient client = new AsyncHttpClient (); client. get (CONFIG_URL, new AsyncHttpResponseHandler () {@ Override public void onSuccess (String result) {// after successful download, save it to the local directory as the cache file ConfigCache. setUrlCache (result, CONFIG_URL); // UI updates can be followed by showConfig (result);} @ Override public void onFailure (Throwable arg0) {// Based on the cause of failure, whether to display loading failure or read cache again }});}}

In this way, the configuration file can be effectively cached and updated in a timely manner, and supports offline browsing.

VII. Summary
The cache management application of smart phones is common and requires a lot and is one of the effective methods to improve user experience.
Of course, some content in cache management is not described in detail, such as slice cache and cache cleanup. These operations are relatively simple.

Related Article

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.