android 緩存的設置與使用

緩存在app應用中的使用
1,MyApplication

//聲明
Map  dataMap;

MyApplication的onCreate中使用

public void onCreate() {
        super.onCreate();
        dataMap = new HashMap<String, Object>();
}

2,緩存管理類cachMapManager

cachMapManager {

//put 緩存
public synchronized static void putCache(String key, Object object) {
        if (MyApplication.dataMap==null) {
            MyApplication.dataMap = new HashMap<String, Object>();
        }
        MyApplication.dataMap.put(key, object);
    }

//get 緩存
public static Object getCache(Context context,String key) {
        if (MyApplication.dataMap==null) {
            MyApplication.dataMap = new HashMap<String, Object>();
        }
        Object obj=MyApplication.dataMap.get(key);
        if (obj==null) {
            Util.toRestart(context);
            Logout.e("aaa", "緩存數據丟失,重啓程序包");
        }
        return obj;

//是否可以爲空
public static Object getCache(Context context,String key,boolean canEmpty) {
        if (MyApplication.dataMap==null) {
            MyApplication.dataMap = new HashMap<String, Object>();
        }
        Object obj=MyApplication.dataMap.get(key);
        if (!canEmpty && obj==null) {
            Util.toRestart(context);
            Logout.e("aaa", "緩存數據丟失,重啓程序包");
        }
        return obj;
    }

}

3,在其他的activity中,設置緩存有使用

 private class  AAAActivity (){

//使用緩存信息
PresentCachInfo  info = (PresentCachInfo)cacheMapManager.getCache(context,"presentCachinfo");
name = info.getName




/**
*設置緩存信息
/
setCach(){
//實體類
 PresentCachInfo  info = new PresentCachInfo();
 //set信息
 info.setName(zhang);
 cachMapManager.putCach("presentCachinfo",info);
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章