Android简单实现 缓存数据
作者:huagbo 发布时间:2022-11-04 11:30:54
标签:Android,缓存,数据
前言
1、每一种要缓存的数据都是有对应的versionCode,通过versionCode请求网络获取是否需要更新
2、提前将要缓存的数据放入assets文件夹中,打包上线。
缓存设计
代码实现
/**
* Created by huangbo on 2017/6/19.
*
* 主要是缓存的工具类
*
* 缓存设计:
* 0.从内存中读取数据 :0.1 读取成功-> 取出versionCode ->3
* 0.2 读取失败-> 1
*
* 1.从文件中读取数据:1.1读取成成功-> 取出versionCode ->3
* 1.2读取失败-> 2
* 2.从Assets中读取数据:2.1读取成功-> 取出versionCode ->3
* 2.2读取失败-> versionCode==0 ->3
*
* 3.用versionCode请求网络 3.1请求成功(有版本更新)将文件写入内存,写入文件;
* 3.1 请求失败,(没有版本更新)
*
*/
public class CacheData {
public static CacheData cacheData;
public static CacheData getInstance() {
if (cacheData == null) {
cacheData = new CacheData();
}
return cacheData;
}
String mFileName;
public CacheData cacheName(String mFileName) {
this.mFileName = mFileName;
return this;
}
ExecutorService cachedThreadPool;
private CacheData() {
cachedThreadPool = Executors.newCachedThreadPool();
}
/**
* 从assets 中读取文件
*
* @return cacheData 的Json串
*/
private String readDataFromAssets() {
try {
InputStream ips = AppUtils.ApplicationContext.getAssets().open(mFileName);
byte[] bytes = new byte[ips.available()];
ips.read(bytes);
ips.close();
return new String(bytes);
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
public void readDataFromAssets(final Handler handler) {
cachedThreadPool.execute(new Runnable() {
@Override
public void run() {
String json = readDataFromAssets();
Message message = handler.obtainMessage(1, json);
handler.sendMessage(message);
}
});
}
public void readDataFromFile(final Handler handler) {
cachedThreadPool.execute(new Runnable() {
@Override
public void run() {
Message message = handler.obtainMessage(1, readDataFromFile());
handler.sendMessage(message);
}
});
}
/**
* 将region 更新到指定文件里
* @param
*/
public void writeData2FileWithThread(final String Data) {
cachedThreadPool.execute(new Runnable() {
@Override
public void run() {
writeRegion2File(Data);
}
});
}
/**
* @return cacheData 的Json串
*/
private String readDataFromFile() {
try {
File file = new File(AppUtils.getCacheDirectory(), mFileName);
if (!file.exists()) {
return null;
}
FileInputStream fis = new FileInputStream(file);
byte[] bytes = new byte[fis.available()];
fis.read(bytes);
fis.close();
return new String(bytes);
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
private void writeData2File(String jsonData) {
try {
File cityFile = new File(AppUtils.getCacheDirectory(), mFileName);
if (!cityFile.exists()) {
cityFile.createNewFile();
}
FileOutputStream fos = new FileOutputStream(cityFile);
fos.write(regionJsonData.getBytes("UTF-8"));
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
使用方法
/**
* Created by huangbo on 2017/6/8.
*/
public class Region {
public static Region region;
public static Region getInstance() {
if (region == null) {
region = new Region();
}
return region;
}
ProvinceCityBean provinceCityBean;
public int getVersion() {
return provinceCityBean == null ? 0 : provinceCityBean.getVersion();
}
public ProvinceCityBean getProvinceCityBean() {
return provinceCityBean;
}
public void setProvinceCityBean(final String mRegionJson, final Handler handler) {
if (TextUtils.isEmpty(mRegionJson)) {
return;
}
cachedThreadPool.execute(new Runnable() {
@Override
public void run() {
provinceCityBean = GsonUtils.GsonToBean(mRegionJson, ProvinceCityBean.class);
if (handler != null) {
handler.sendEmptyMessage(1);
}
}
});
}
ExecutorService cachedThreadPool;
CacheData cacheData;
private Region() {
cachedThreadPool = Executors.newCachedThreadPool();
cacheData = CacheData.getInstance().cacheName(Const.REGION_JSON);
}
/**
* 具体调用方法
*/
public void cacheRegion() {
if (provinceCityBean == null) {
readRegionFromFile();
} else {
readRegionFromHttp();
}
}
private void readRegionFromFile() {
cacheData.readDataFromFile(new Handler() {
@Override
public void handleMessage(Message msg) {
String jsonRegion = (String) msg.obj;
onReadRegionFromFileBack(jsonRegion);
}
});
}
/**
* 从文件中读取数据,若为null 继续从Asset中获取
*
* @param jsonRegion
*/
private void onReadRegionFromFileBack(String jsonRegion) {
if (!TextUtils.isEmpty(jsonRegion)) {/*文件中读取成功 设置到Region中更新json 取出version请求网络判断是否为最新的版本 */
setProvinceCityBean(jsonRegion, httpHandler);
} else {/*文件中读取失败 从assets 中继续读取*/
cacheData.readDataFromAssets(new Handler() {
@Override
public void handleMessage(Message msg) {
String jsonRegion = (String) msg.obj;
onReadRegionFromAssetsBack(jsonRegion);
}
});
}
}
private void onReadRegionFromAssetsBack(String jsonRegion) {
if (!TextUtils.isEmpty(jsonRegion)) {/*从assets中读取成功 设置到Region中更新json*/
setProvinceCityBean(jsonRegion, httpHandler);
} else {
readRegionFromHttp();
}
}
private void readRegionFromHttp() {
ReqRegion reqRegion = new ReqRegion();
reqRegion.sendRequest(false, new OnHttpResult() {
@Override
public void onHttpSuccess(String data) {
setProvinceCityBean(data, null);
cacheData.writeData2FileWithThread(data);
}
@Override
public void onHttpFailure(String message) {
}
});
}
Handler httpHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
readRegionFromHttp();
}
};
}
Region.getInstance().cacheRegion();//实现缓存
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。如有错误或未考虑完全的地方,望不吝赐教。
来源:https://blog.csdn.net/huagbo/article/details/76131000


猜你喜欢
- C#事件标准命名规则一些开源代码的事件命名很混乱,以此文章用作本人以后工作的参考。事件的名称事件始终是指某个操作,这个操作可能正在发生,也可
- 定义:"Lambda表达式"是一个匿名函数,是一种高效的类似于函数式编程的表达式。好处:Lambda简化了匿名委托的使用
- Java是如何跳出当前多重循环?不建议使用在最外层前面加一个标记A,然后用break A;可以跳出多重循环因为它不会让你的程序变得更加优雅,
- 在实际业务中,当后台数据发生变化,客户端能够实时的收到通知,而不是由用户主动的进行页面刷新才能查看,这将是一个非常人性化的设计。有没有那么一
- 主要用的是org.apache.tools.zip.ZipOutputStream 这个zip流,这里以Execl为例子。思路首
- 前言我们在日常开发中,经常会用到一个系统需要链接多个数据库来实现业务的需求,比如多个系统之间数据调用、两个数据之间同步等等。今天给大家分享使
- Java绘图中,显示文字的方法主要有三种:(1)drawString(String str,int x,int y):在指定的位置显示字符串
- 很多项目需要用到弹幕效果,尤其是在播放视频的时候需要一起显示别人发的弹幕,也包括自己的发的。今天就试着写了一下这个效果。思路就是将从右往左的
- 实例如下:import java.lang.reflect.Field;import java.lang.reflect.Invocatio
- 一、异常分类 java异常分为"检查"
- 本文实例总结了C#配置文件Section节点处理方法。分享给大家供大家参考。具体如下:很多时候在项目开发中,我们都需要用配置文件来存储一些关
- 本文根据java开发人员在编码过程中容易忽视或经常出错的地方进行了整理,总结了十个比较常见的低级错误点,方便大家学习。1、不能用“==”比较
- 1、回顾一下大家有没有注意到,目前讲到的所有 controller 中的方法接收到请求之后,都是有返回值的,返回值主要有 2 种类型:1、
- 前言偶然逛国外博客,看到了一个介绍文字动画的库,进入 pub 一看,立马就爱上这个动画库了,几乎你能想到的文字动画效果它都有!现在正式给大家
- 最近项目上产品经理提了个需求,要求关闭语言国际化,不管手机系统设置那个国家的语言,都要显示汉语,好吧,既然有需求,那就做吧。但是项目中已经有
- 一、加载注册流程1.在dispatch-servlet.xml中配置< mvc:annotation-driven/>,在控制器
- 根据用户系统时区动态展示时间当我们使用SpringBoot+Mysql开发系统时,总是统一设置UTC+8时区,这样用户在任何地区访问系统,展
- 前言如果在开发过程中,你还在靠查看服务器日志来寻找服务与服务之间的报错信息,那么这篇一定要来看下,通常在我们开发环境自测的时候,我们会将代码
- 在构造函数里加上以下代码:this.DoubleBuffered = true;//设置本窗体SetStyle(ControlStyles.
- 本文实例为大家分享了ImageSwitcher图像切换器的实现代码,供大家参考,具体内容如下描述在该实例中,提供一个图片切换器和两个点击按钮