软件编程
位置:首页>> 软件编程>> Android编程>> Android简单实现 缓存数据

Android简单实现 缓存数据

作者:huagbo  发布时间:2022-11-04 11:30:54 

标签:Android,缓存,数据

前言

1、每一种要缓存的数据都是有对应的versionCode,通过versionCode请求网络获取是否需要更新

2、提前将要缓存的数据放入assets文件夹中,打包上线。

缓存设计

Android简单实现 缓存数据

代码实现


/**
* 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

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com