您的位置:首页 > 移动开发 > Android开发

【oschina android源码分析】缓存的设计

2016-05-18 17:06 363 查看
CacheManager就是它整体的缓存设计。

方案:以TeamMemberFragment为例:

1.初始时(onCreateView时)先从缓存中取数据

TeamMemberList list = (TeamMemberList)CacheManager.readObject(aty,TEAM_MEMBER_DATA);


/**
* 读取对象
*
* @param file
* @return
* @throws IOException
*/
public static Serializable readObject(Context context, String file) {
if (!isExistDataCache(context, file))
return null;
FileInputStream fis = null;
ObjectInputStream ois = null;
try {
fis = context.openFileInput(file);
ois = new ObjectInputStream(fis);
return (Serializable) ois.readObject();
} catch (FileNotFoundException e) {
} catch (Exception e) {
e.printStackTrace();
// 反序列化失败 - 删除缓存文件
if (e instanceof InvalidClassException) {
File data = context.getFileStreamPath(file);
data.delete();
}
} finally {
try {
ois.close();
} catch (Exception e) {
}
try {
fis.close();
} catch (Exception e) {
}
}
return null;
}


缓存有有效期。具体的计算方案:

/**
* 判断缓存是否已经失效
*/
public static boolean isCacheDataFailure(Context context, String cachefile) {
File data = context.getFileStreamPath(cachefile);
if (!data.exists()) {

return false;
}
long existTime = System.currentTimeMillis() - data.lastModified();
boolean failure = false;
if (TDevice.getNetworkType() == TDevice.NETTYPE_WIFI) {
failure = existTime > wifi_cache_time ? true : false;
} else {
failure = existTime > other_cache_time ? true : false;
}
return failure;
}


根据TeamMemberFragment_key+team.getId()去取那条数据。

2.如果取到的缓存为空,则联网去取数据

数据请求成功以后会把列表对象保存下来:

CacheManager.saveObject(aty, list,
 TEAM_MEMBER_DATA);


/**
* 保存对象
*
* @param ser
* @param file
* @throws IOException
*/
public static boolean saveObject(Context context, Serializable ser,
String file) {
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try {
fos = context.openFileOutput(file, Context.MODE_PRIVATE);
oos = new ObjectOutputStream(fos);
oos.writeObject(ser);
oos.flush();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
try {
oos.close();
} catch (Exception e) {
}
try {
fos.close();
} catch (Exception e) {
}
}
}


采用的是序列化的方式。

存储的位置:内存中data/data/应用包名/files下,是直接把对象存了下来。

命名方式:TeamMemberFragment_key+team.getId()

3.下拉刷新时,会把新的一页保存下来

命名方式:TeamMemberFragment_key+team.getId(),相当于旧的直接被更新了。

4.缓存的清理时机

缓存的主要清理时机是:在设置里面有一个选项叫做清理缓存,点击它即可清理缓存。新开启一个线程来执行以下操作。

AppContext.getInstance().clearAppCache();


DataCleanManager.cleanDatabases(this);
// 清除数据缓存
DataCleanManager.cleanInternalCache(this);


因为oschina的便笺存储采用的是数据库存储方案。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: