欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Android簡(jiǎn)單實(shí)現(xiàn) 緩存數(shù)據(jù)

 更新時(shí)間:2021年05月06日 10:21:13   作者:huagbo  
這篇文章主要介紹了Android簡(jiǎn)單實(shí)現(xiàn) 緩存數(shù)據(jù),小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧

前言

1、每一種要緩存的數(shù)據(jù)都是有對(duì)應(yīng)的versionCode,通過(guò)versionCode請(qǐng)求網(wǎng)絡(luò)獲取是否需要更新

2、提前將要緩存的數(shù)據(jù)放入assets文件夾中,打包上線。

緩存設(shè)計(jì)

Android 緩存流程圖

代碼實(shí)現(xiàn)

/**
 * Created by huangbo on 2017/6/19.
 *
 * 主要是緩存的工具類
 *
 * 緩存設(shè)計(jì):
 *         0.從內(nèi)存中讀取數(shù)據(jù) :0.1 讀取成功-> 取出versionCode ->3
 *                             0.2 讀取失敗-> 1
 *
 *         1.從文件中讀取數(shù)據(jù):1.1讀取成成功-> 取出versionCode ->3
 *                             1.2讀取失敗-> 2
 *         2.從Assets中讀取數(shù)據(jù):2.1讀取成功-> 取出versionCode ->3
 *                                2.2讀取失敗-> versionCode==0 ->3
 *
 *         3.用versionCode請(qǐng)求網(wǎng)絡(luò) 3.1請(qǐng)求成功(有版本更新)將文件寫入內(nèi)存,寫入文件;
 *                                 3.1 請(qǐng)求失敗,(沒(méi)有版本更新)
 *
 */

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);
    }


    /**
     * 具體調(diào)用方法
     */
    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);
            }
        });
    }

    /**
     * 從文件中讀取數(shù)據(jù),若為null 繼續(xù)從Asset中獲取
     *
     * @param jsonRegion
     */
    private void onReadRegionFromFileBack(String jsonRegion) {
        if (!TextUtils.isEmpty(jsonRegion)) {/*文件中讀取成功 設(shè)置到Region中更新json 取出version請(qǐng)求網(wǎng)絡(luò)判斷是否為最新的版本 */
            setProvinceCityBean(jsonRegion, httpHandler);
        } else {/*文件中讀取失敗  從assets 中繼續(xù)讀取*/
            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中讀取成功 設(shè)置到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();//實(shí)現(xiàn)緩存

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教。

相關(guān)文章

最新評(píng)論