Android简单实现 缓存数据
作者:huagbo 时间:2022-11-04 11:30:54
前言
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
标签:Android,缓存,数据
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Android开发使用RecyclerView添加点击事件实例详解
2022-04-30 14:11:55
SpringBoot上传文件大小受限问题的解决办法
2023-04-19 09:46:16
![](https://img.aspxhome.com/file/2023/9/63629_0s.jpg)
Android中butterknife的使用与自动化查找组件插件详解
2021-09-18 06:58:36
![](https://img.aspxhome.com/file/2023/3/137713_0s.jpg)
Mybatis 中的sql批量修改方法实现
2022-12-10 23:36:51
SpringBoot2.x 参数校验问题小结
2023-05-22 02:21:22
![](https://img.aspxhome.com/file/2023/7/61567_0s.png)
android实现歌词自动滚动效果
2022-03-16 17:09:10
![](https://img.aspxhome.com/file/2023/7/138797_0s.jpg)
基于springboot+vue实现垃圾分类管理系统
2023-04-17 08:39:11
![](https://img.aspxhome.com/file/2023/2/86862_0s.jpg)
Java实现查找算法的示例代码(二分查找、插值查找、斐波那契查找)
2022-05-28 04:17:38
![](https://img.aspxhome.com/file/2023/0/86830_0s.png)
C#探秘系列(一)——ToDictionary,ToLookup
2023-04-19 09:16:15
![](https://img.aspxhome.com/file/2023/2/100092_0s.png)
基于Ok+Rxjava+retrofit实现断点续传下载
2021-08-27 02:21:49
![](https://img.aspxhome.com/file/2023/5/108435_0s.jpg)
因Spring AOP导致@Autowired依赖注入失败的解决方法
2022-10-24 19:44:11
MyBatis配置的应用与对比jdbc的优势
2023-08-27 07:03:47
![](https://img.aspxhome.com/file/2023/1/58281_0s.png)
面试Spring中的bean线程是否安全及原因
2021-06-11 18:25:38
Android实现图片文字轮播特效
2021-07-25 18:44:11
![](https://img.aspxhome.com/file/2023/0/122060_0s.jpg)
在java poi导入Excel通用工具类示例详解
2022-11-11 21:16:00
![](https://img.aspxhome.com/file/2023/6/66646_0s.png)
java随机验证码生成实现实例代码
2022-05-18 03:03:31
c#简单读取文本的实例方法
2022-02-16 14:51:52
Spring中的aware接口详情
2023-11-29 10:48:29
![](https://img.aspxhome.com/file/2023/9/60689_0s.webp)
Java动态规划方式解决不同的二叉搜索树
2023-03-02 01:56:52
![](https://img.aspxhome.com/file/2023/1/128231_0s.png)
springBoot @Scheduled实现多个任务同时开始执行
2023-06-19 23:16:41
![](https://img.aspxhome.com/file/2023/7/94337_0s.png)