判断sd卡是否存在:
if(!CacheService.isSdCardExist()){
Toast.makeText(UserLoginActivity.this, "未找到SD卡",
Toast.LENGTH_SHORT).show();
}
存数据:
CacheDataUtil.saveCacheData(dataList,Constants.DATA_CUSTOMER_LIST);
取数据:
dataList=CacheDataUtil.getCacheData(this, Constants.DATA_CUSTOMER_LIST);
使用的两个工具类分别是:CacheDataUtil,CacheUtil
public class CacheUtil {
private static final long INITIALCRC = 0xFFFFFFFFFFFFFFFFL; private static long[] CRCTable = new long[256]; private static boolean init = false; private static final long POLY64REV = 0x95AC9329AC4BC9B5L; /** * A function thats returns a 64-bit crc for string * * @param in * : input string * @return 64-bit crc value */ public static final long Crc64Long(String in) { if (in == null || in.length() == 0) { return 0; } // http://bioinf.cs.ucl.ac.uk/downloads/crc64/crc64.c long crc = INITIALCRC, part; if (!init) { for (int i = 0; i < 256; i++) { part = i; for (int j = 0; j < 8; j++) { int value = ((int) part & 1); if (value != 0) part = (part >> 1) ^ POLY64REV; else part >>= 1; } CRCTable[i] = part; }init = true; } int length = in.length(); for (int k = 0; k < length; ++k) { char c = in.charAt(k); crc = CRCTable[(((int) crc) ^ c) & 0xff] ^ (crc >> 8); } return crc; }
}
CacheDataUtil 工具类
/** * 本地缓存处理方法 * @author Administrator * */public class CacheDataUtil {
/** * 保存对象数组到本地 */ public static boolean saveCacheData(ArrayList<Parcelable> dataList, String Key){ Long cacheKey = CacheUtil.Crc64Long(Key); CacheService.sDataCache.delete(cacheKey); if (dataList.size() > 0 && cacheKey != 0 && CacheService.sDataCache != null) { CacheService.sDataCache.flush(); Parcel parcel = Parcel.obtain(); parcel.writeList(dataList); byte[] bytes = parcel.marshall(); if (bytes != null && bytes.length > 0) { CacheService.sDataCache.put(cacheKey,bytes, 0); CacheService.sDataCache.flush(); } parcel.recycle(); } return true; } /** * 获取本地所有的对象 */ @SuppressWarnings("unchecked") public static ArrayList<Parcelable> getCacheData(Context context,String Key){ ArrayList<Parcelable> list = null; // 首先读取用户相关门店缓存应用信息 Long cacheKey = CacheUtil.Crc64Long(Key); byte[] datas = CacheService.sDataCache != null ? CacheService.sDataCache .get(cacheKey,0) : null; if (datas != null && datas.length > 0) { Parcel parcel = Parcel.obtain(); parcel.unmarshall(datas, 0, datas.length); parcel.setDataPosition(0); list = parcel.readArrayList(context.getClass().getClassLoader()); parcel.recycle(); } if (list == null) { list = new ArrayList<Parcelable>(); }else{ Iterator<Parcelable> iterator = list.iterator(); while(iterator.hasNext()){ if(null==iterator.next()){ iterator.remove(); } } } return list; } /** * 清除 */ public static void clearAllCacheData() { CacheService.sDataCache.deleteAll();; } }