开源中国 OsChina Android 客户端源码分析(11)缓存对象

客户端源码中用来缓存对象的类为CacheManager

1 缓存的好处:想想微信,断网的情况下,打开APP后,依然有历史的聊天记录;

2缓存的就是 各种对象。缓存到哪里呢?  

2.1手机内置私有app目录下的缓存目录;

2.2手机SD卡私有app目录下的缓存目录;

2.3手机SD卡公有的指定目录。

3要实现对对象缓存,使对象持久化,需要对象实现Serializable接口。

4该类中提供了,对象缓存,读取缓存对象,判断缓存是否存在,缓存是否过期四个功能。其中不同的网络环境下缓存的有效期设置的不同,这个需要根据业务去设置。

5 缓存对象的源码:

context 根据路径获取文件输出流

ser 待保存的对象

file 文件路径

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) {

   }

}

    }

6 缓存失效判断

6.1 如果保存缓存的文件不存在了 也认为缓存失效

6.2 根据不同的网络类型,做不同的失效性判断。用系统当前时间-缓存文件上一次操作的时间。用lastModified()方法即可获得文件上一次操作的时间。

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;

    }


你可能感兴趣的:(android,开源中国,缓存对象)