由于每次打开应用之前,我们发现可以加载上次缓存的内容,所以我们这次来设置如何进行网络访问数据的缓存。
实现目的:在第一次打开该应用时进行数据缓存,在第二次打开该应用时,如果发现存在缓存的数据,即加载这部分的数据,再过2分钟开始,刷新网络的数据。
1、在 CacheUtils设置缓存string、long等数据。
CacheUtils.java
package huaxa.it.zhihuidemo.utils;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
/**
* @项目名: ZhiHuiDemo
* @包名: huaxa.it.zhihuidemoUtils
* @类名: CacheUtils
* @创建者: 黄夏莲
* @创建时间: 2016年10月3日 ,下午6:09:45
*
* @描述:跳转页面
*
*/
public class CacheUtils
{
private final static String sharedPreferencesName = "zhbj";
private static SharedPreferences mpreferences; // 静态的,从内存取(只需取1次),比读文件快(每次都要读取)
private static SharedPreferences getsp(Context context)
{
if (mpreferences == null)
{
mpreferences = context.getSharedPreferences(sharedPreferencesName,
Context.MODE_PRIVATE);
}
return mpreferences;
}
/**
* 通过sp获得boolean类型的数据,没有默认为false
*
* @param context
* :上下文
* @param key
* :存储的key
* @return
*/
public static boolean getBoolean(Context context, String key)
{
// TODO Auto-generated method stub
// SharedPreferences mpreferences = context.getSharedPreferences(
// sharedPreferencesName, Context.MODE_PRIVATE);
mpreferences = getsp(context);
return mpreferences.getBoolean(key, false<