获取缓存的大小和清除缓存是每个APP都会用的的,下面我们来看看怎么做呢::::
1.首先,我们要写一个清除缓存大小的工具类:
DataCleanManager.class
import java.io.File;
import java.math.BigDecimal;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Environment;
import android.text.TextUtils;
/**
* 获取缓存文件大小及清除缓存
*
* @author zhangjingjing
* @date 2016-7-18
*/
public class DataCleanManager {
/**
* * 清除本应用内部缓存(/data/data/com.xxx.xxx/cache) * *
*
* @param context
*/
public static void cleanInternalCache(Context context) {
deleteFilesByDirectory(context.getCacheDir());
}
/**
* * 清除本应用所有数据库(/data/data/com.xxx.xxx/databases) * *
*
* @param context
*/
@SuppressLint("SdCardPath")
public static void cleanDatabases(Context context) {
deleteFilesByDirectory(new File("/data/data/"
+ context.getPackageName() + "/databases"));
}
/**
* * 清除本应用SharedPreference(/data/data/com.xxx.xxx/shared_prefs) *
*
* @param context
*/
@SuppressLint("SdCardPath")
public static void cleanSharedPreference(Context context) {
deleteFilesByDirectory(new File("/data/data/"
+ context.getPackageName() + "/shared_prefs"));
}
/**
* * 按名字清除本应用数据库 * *
*
* @param context
* @param dbName
*/
public static void cleanDatabaseByName(Context context, String dbName) {
context.deleteDatabase(dbName);
}
/**
* * 清除/data/data/com.xxx.xxx/files下的内容 * *
*
* @param context
*/
public static void cleanFiles(Context context) {
deleteFilesByDirectory(context.getFilesDir());
}
/**
* * 清除外部cache下的内容(/mnt/sdcard/android/data/com.xxx.xxx/cache)
*
* @param context
*/
public static void cleanExternalCache(Context context) {
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
deleteFilesByDirectory(context.getExternalCacheDir());
}
}
/**
* * 清除自定义路径下的文件,使用需小心,请不要误删。而且只支持目录下的文件删除 * *
*
* @param filePath
* */
public static void cleanCustomCache(String filePath) {
deleteFilesByDirectory(new File(filePath));
}
/**
* * 清除本应用所有的数据 * *
*
* @param context
* @param filepath
*/
public static void cleanApplicationData(Context context, String... filepath) {
cleanInternalCache(context);
cleanExternalCache(context);
cleanDatabases(context);
cleanSharedPreference(context);
cleanFiles(context);
if (filepath == null) {
return;
}
for (String filePath : filepath) {
cleanCustomCache(filePath);
}
}
/**
* * 删除方法 这里只会删除某个文件夹下的文件,如果传入的directory是个文件,将不做处理 * *
*
* @param directory
*/
private static void deleteFilesByDirectory(File directory) {
if (directory != null && directory.exists() && directory.isDirectory()) {
for (File item : directory.listFiles()) {
item.delete();
}
}
}
// 获取文件
// Context.getExternalFilesDir() --> SDCard/Android/data/你的应用的包名/files/
// 目录,一般放一些长时间保存的数据
// Context.getExternalCacheDir() -->
// SDCard/Android/data/你的应用包名/cache/目录,一般存放临时缓存数据
public static long getFolderSize(File file) throws Exception {
long size = 0;
try {
File[] fileList = file.listFiles();
for (int i = 0; i < fileList.length; i++) {
// 如果下面还有文件
if (fileList[i].isDirectory()) {
size = size + getFolderSize(fileList[i]);
} else {
size = size + fileList[i].length();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return size;
}
/**
* 删除指定目录下文件及目录
*
* @param deleteThisPath
* @param filepath
* @return
*/
public static void deleteFolderFile(String filePath, boolean deleteThisPath) {
if (!TextUtils.isEmpty(filePath)) {
try {
File file = new File(filePath);
if (file.isDirectory()) {// 如果下面还有文件
File files[] = file.listFiles();
for (int i = 0; i < files.length; i++) {
deleteFolderFile(files[i].getAbsolutePath(), true);
}
}
if (deleteThisPath) {
if (!file.isDirectory()) {// 如果是文件,删除
file.delete();
} else {// 目录
if (file.listFiles().length == 0) {// 目录下没有文件或者目录,删除
file.delete();
}
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* 格式化单位
*
* @param size
* @return
*/
public static String getFormatSize(double size) {
double kiloByte = size / 1024;
if (kiloByte < 1) {
return size + "Byte";
}
double megaByte = kiloByte / 1024;
if (megaByte < 1) {
BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
return result1.setScale(2, BigDecimal.ROUND_HALF_UP)
.toPlainString() + "KB";
}
double gigaByte = megaByte / 1024;
if (gigaByte < 1) {
BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
return result2.setScale(2, BigDecimal.ROUND_HALF_UP)
.toPlainString() + "MB";
}
double teraBytes = gigaByte / 1024;
if (teraBytes < 1) {
BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
return result3.setScale(2, BigDecimal.ROUND_HALF_UP)
.toPlainString() + "GB";
}
BigDecimal result4 = new BigDecimal(teraBytes);
return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()
+ "TB";
}
/**
* 获取文件大小
*
* @param file
* @return
* @throws Exception
*/
public static String getCacheSize(File file) throws Exception {
return getFormatSize(getFolderSize(file));
}
}
2.接着我们要写获取缓存大小的方法,一定要在oncreat方法中调用这个方法
getFileSize();// 调用获取缓存大小的方法
/**
* 获取缓存文件大小并设置在控件上
*/
private void getFileSize() {
// TODO Auto-generated method stub
try {
cacheSize = DataCleanManager.getCacheSize(this.getCacheDir());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
tv_data.setText("已缓存" + cacheSize);
}
3.在接着就在点击事件的监听里写逻辑啦:
ACache aCache = ACache.get(Install_Activity.this);
aCache.clear();// 先清除缓存
// 获取文件大小
getFileSize();
Toast.makeText(Install_Activity.this, "已清除缓存", 0).show();
4.这个是缓存的工具类:ACache.class
/**
* 缓存工具类
*/
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.RandomAccessFile;
import java.io.Serializable;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import org.json.JSONArray;
import org.json.JSONObject;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
/**
* @author Michael Yang锛坵ww.yangfuhai.com锛�update at 2013.08.07
*/
public class ACache {
public static final int TIME_HOUR = 60 * 60;
public static final int TIME_DAY = TIME_HOUR * 24;
private static final int MAX_SIZE = 1000 * 1000 * 50; // 50 mb
private static final int MAX_COUNT = Integer.MAX_VALUE; // 涓嶉檺鍒跺瓨鏀炬暟鎹殑鏁伴噺
private static Map<String, ACache> mInstanceMap = new HashMap<String, ACache>();
private ACacheManager mCache;
public static ACache get(Context ctx) {
return get(ctx, "ACache");
}
public static ACache get(Context ctx, String cacheName) {
File f = new File(ctx.getCacheDir(), cacheName);
return get(f, MAX_SIZE, MAX_COUNT);
}
public static ACache get(File cacheDir) {
return get(cacheDir, MAX_SIZE, MAX_COUNT);
}
public static ACache get(Context ctx, long max_zise, int max_count) {
File f = new File(ctx.getCacheDir(), "ACache");
return get(f, max_zise, max_count);
}
public static ACache get(File cacheDir, long max_zise, int max_count) {
ACache manager = mInstanceMap.get(cacheDir.getAbsoluteFile() + myPid());
if (manager == null) {
manager = new ACache(cacheDir, max_zise, max_count);
mInstanceMap.put(cacheDir.getAbsolutePath() + myPid(), manager);
}
return manager;
}
private static String myPid() {
return "_" + android.os.Process.myPid();
}
private ACache(File cacheDir, long max_size, int max_count) {
if (!cacheDir.exists() && !cacheDir.mkdirs()) {
throw new RuntimeException("can't make dirs in "
+ cacheDir.getAbsolutePath());
}
mCache = new ACacheManager(cacheDir, max_size, max_count);
}
// =======================================
// ============ String鏁版嵁 璇诲啓 ==============
// =======================================
/**
* 淇濆瓨 String鏁版嵁 鍒�缂撳瓨涓�
*
* @param key
* 淇濆瓨鐨刱ey
* @param value
* 淇濆瓨鐨凷tring鏁版嵁
*/
public void put(String key, String value) {
File file = mCache.newFile(key);
BufferedWriter out = null;
try {
out = new BufferedWriter(new FileWriter(file), 1024);
out.write(value);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
mCache.put(file);
}
}
/**
* 淇濆瓨 String鏁版嵁 鍒�缂撳瓨涓�
*
* @param key
* 淇濆瓨鐨刱ey
* @param value
* 淇濆瓨鐨凷tring鏁版嵁
* @param saveTime
* 淇濆瓨鐨勬椂闂达紝鍗曚綅锛氱
*/
public void put(String key, String value, int saveTime) {
put(key, Utils.newStringWithDateInfo(saveTime, value));
}
/**
* 璇诲彇 String鏁版嵁
*
* @param key
* @return String 鏁版嵁
*/
public String getAsString(String key) {
File file = mCache.get(key);
if (!file.exists())
return null;
boolean removeFile = false;
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(file));
String readString = "";
String currentLine;
while ((currentLine = in.readLine()) != null) {
readString += currentLine;
}
if (!Utils.isDue(readString)) {
return Utils.clearDateInfo(readString);
} else {
removeFile = true;
return null;
}
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (removeFile)
remove(key);
}
}
// =======================================
// ============= JSONObject 鏁版嵁 璇诲啓 ==============
// =======================================
/**
* 淇濆瓨 JSONObject鏁版嵁 鍒�缂撳瓨涓�
*
* @param key
* 淇濆瓨鐨刱ey
* @param value
* 淇濆瓨鐨凧SON鏁版嵁
*/
public void put(String key, JSONObject value) {
put(key, value.toString());
}
/**
* 淇濆瓨 JSONObject鏁版嵁 鍒�缂撳瓨涓�
*
* @param key
* 淇濆瓨鐨刱ey
* @param value
* 淇濆瓨鐨凧SONObject鏁版嵁
* @param saveTime
* 淇濆瓨鐨勬椂闂达紝鍗曚綅锛氱
*/
public void put(String key, JSONObject value, int saveTime) {
put(key, value.toString(), saveTime);
}
/**
* 璇诲彇JSONObject鏁版嵁
*
* @param key
* @return JSONObject鏁版嵁
*/
public JSONObject getAsJSONObject(String key) {
String JSONString = getAsString(key);
try {
JSONObject obj = new JSONObject(JSONString);
return obj;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
// =======================================
// ============ JSONArray 鏁版嵁 璇诲啓 =============
// =======================================
/**
* 淇濆瓨 JSONArray鏁版嵁 鍒�缂撳瓨涓�
*
* @param key
* 淇濆瓨鐨刱ey
* @param value
* 淇濆瓨鐨凧SONArray鏁版嵁
*/
public void put(String key, JSONArray value) {
put(key, value.toString());
}
/**
* 淇濆瓨 JSONArray鏁版嵁 鍒�缂撳瓨涓�
*
* @param key
* 淇濆瓨鐨刱ey
* @param value
* 淇濆瓨鐨凧SONArray鏁版嵁
* @param saveTime
* 淇濆瓨鐨勬椂闂达紝鍗曚綅锛氱
*/
public void put(String key, JSONArray value, int saveTime) {
put(key, value.toString(), saveTime);
}
/**
* 璇诲彇JSONArray鏁版嵁
*
* @param key
* @return JSONArray鏁版嵁
*/
public JSONArray getAsJSONArray(String key) {
String JSONString = getAsString(key);
try {
JSONArray obj = new JSONArray(JSONString);
return obj;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
// =======================================
// ============== byte 鏁版嵁 璇诲啓 =============
// =======================================
/**
* 淇濆瓨 byte鏁版嵁 鍒�缂撳瓨涓�
*
* @param key
* 淇濆瓨鐨刱ey
* @param value
* 淇濆瓨鐨勬暟鎹�
*/
public void put(String key, byte[] value) {
File file = mCache.newFile(key);
FileOutputStream out = null;
try {
out = new FileOutputStream(file);
out.write(value);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
mCache.put(file);
}
}
/**
* 淇濆瓨 byte鏁版嵁 鍒�缂撳瓨涓�
*
* @param key
* 淇濆瓨鐨刱ey
* @param value
* 淇濆瓨鐨勬暟鎹�
* @param saveTime
* 淇濆瓨鐨勬椂闂达紝鍗曚綅锛氱
*/
public void put(String key, byte[] value, int saveTime) {
put(key, Utils.newByteArrayWithDateInfo(saveTime, value));
}
/**
* 鑾峰彇 byte 鏁版嵁
*
* @param key
* @return byte 鏁版嵁
*/
public byte[] getAsBinary(String key) {
RandomAccessFile RAFile = null;
boolean removeFile = false;
try {
File file = mCache.get(key);
if (!file.exists())
return null;
RAFile = new RandomAccessFile(file, "r");
byte[] byteArray = new byte[(int) RAFile.length()];
RAFile.read(byteArray);
if (!Utils.isDue(byteArray)) {
return Utils.clearDateInfo(byteArray);
} else {
removeFile = true;
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (RAFile != null) {
try {
RAFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (removeFile)
remove(key);
}
}
// =======================================
// ============= 搴忓垪鍖�鏁版嵁 璇诲啓 ===============
// =======================================
/**
* 淇濆瓨 Serializable鏁版嵁 鍒�缂撳瓨涓�
*
* @param key
* 淇濆瓨鐨刱ey
* @param value
* 淇濆瓨鐨剉alue
*/
public void put(String key, Serializable value) {
put(key, value, -1);
}
/**
* 淇濆瓨 Serializable鏁版嵁鍒�缂撳瓨涓�
*
* @param key
* 淇濆瓨鐨刱ey
* @param value
* 淇濆瓨鐨剉alue
* @param saveTime
* 淇濆瓨鐨勬椂闂达紝鍗曚綅锛氱
*/
public void put(String key, Serializable value, int saveTime) {
ByteArrayOutputStream baos = null;
ObjectOutputStream oos = null;
try {
baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);
oos.writeObject(value);
byte[] data = baos.toByteArray();
if (saveTime != -1) {
put(key, data, saveTime);
} else {
put(key, data);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
oos.close();
} catch (IOException e) {
}
}
}
/**
* 璇诲彇 Serializable鏁版嵁
*
* @param key
* @return Serializable 鏁版嵁
*/
public Object getAsObject(String key) {
byte[] data = getAsBinary(key);
if (data != null) {
ByteArrayInputStream bais = null;
ObjectInputStream ois = null;
try {
bais = new ByteArrayInputStream(data);
ois = new ObjectInputStream(bais);
Object reObject = ois.readObject();
return reObject;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
try {
if (bais != null)
bais.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (ois != null)
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
// =======================================
// ============== bitmap 鏁版嵁 璇诲啓 =============
// =======================================
/**
* 淇濆瓨 bitmap 鍒�缂撳瓨涓�
*
* @param key
* 淇濆瓨鐨刱ey
* @param value
* 淇濆瓨鐨刡itmap鏁版嵁
*/
public void put(String key, Bitmap value) {
put(key, Utils.Bitmap2Bytes(value));
}
/**
* 淇濆瓨 bitmap 鍒�缂撳瓨涓�
*
* @param key
* 淇濆瓨鐨刱ey
* @param value
* 淇濆瓨鐨�bitmap 鏁版嵁
* @param saveTime
* 淇濆瓨鐨勬椂闂达紝鍗曚綅锛氱
*/
public void put(String key, Bitmap value, int saveTime) {
put(key, Utils.Bitmap2Bytes(value), saveTime);
}
/**
* 璇诲彇 bitmap 鏁版嵁
*
* @param key
* @return bitmap 鏁版嵁
*/
public Bitmap getAsBitmap(String key) {
if (getAsBinary(key) == null) {
return null;
}
return Utils.Bytes2Bimap(getAsBinary(key));
}
// =======================================
// ============= drawable 鏁版嵁 璇诲啓 =============
// =======================================
/**
* 淇濆瓨 drawable 鍒�缂撳瓨涓�
*
* @param key
* 淇濆瓨鐨刱ey
* @param value
* 淇濆瓨鐨刣rawable鏁版嵁
*/
public void put(String key, Drawable value) {
put(key, Utils.drawable2Bitmap(value));
}
/**
* 淇濆瓨 drawable 鍒�缂撳瓨涓�
*
* @param key
* 淇濆瓨鐨刱ey
* @param value
* 淇濆瓨鐨�drawable 鏁版嵁
* @param saveTime
* 淇濆瓨鐨勬椂闂达紝鍗曚綅锛氱
*/
public void put(String key, Drawable value, int saveTime) {
put(key, Utils.drawable2Bitmap(value), saveTime);
}
/**
* 璇诲彇 Drawable 鏁版嵁
*
* @param key
* @return Drawable 鏁版嵁
*/
public Drawable getAsDrawable(String key) {
if (getAsBinary(key) == null) {
return null;
}
return Utils.bitmap2Drawable(Utils.Bytes2Bimap(getAsBinary(key)));
}
/**
* 鑾峰彇缂撳瓨鏂囦欢
*
* @param key
* @return value 缂撳瓨鐨勬枃浠�
*/
public File file(String key) {
File f = mCache.newFile(key);
if (f.exists())
return f;
return null;
}
/**
* 绉婚櫎鏌愪釜key
*
* @param key
* @return 鏄惁绉婚櫎鎴愬姛
*/
public boolean remove(String key) {
return mCache.remove(key);
}
/**
* 娓呴櫎鎵�湁鏁版嵁
*/
public void clear() {
mCache.clear();
}
/**
* @title 缂撳瓨绠$悊鍣�
* @author 鏉ㄧ娴凤紙michael锛�www.yangfuhai.com
* @version 1.0
*/
public class ACacheManager {
private final AtomicLong cacheSize;
private final AtomicInteger cacheCount;
private final long sizeLimit;
private final int countLimit;
private final Map<File, Long> lastUsageDates = Collections
.synchronizedMap(new HashMap<File, Long>());
protected File cacheDir;
private ACacheManager(File cacheDir, long sizeLimit, int countLimit) {
this.cacheDir = cacheDir;
this.sizeLimit = sizeLimit;
this.countLimit = countLimit;
cacheSize = new AtomicLong();
cacheCount = new AtomicInteger();
calculateCacheSizeAndCacheCount();
}
/**
* 璁$畻 cacheSize鍜宑acheCount
*/
private void calculateCacheSizeAndCacheCount() {
new Thread(new Runnable() {
@Override
public void run() {
int size = 0;
int count = 0;
File[] cachedFiles = cacheDir.listFiles();
if (cachedFiles != null) {
for (File cachedFile : cachedFiles) {
size += calculateSize(cachedFile);
count += 1;
lastUsageDates.put(cachedFile,
cachedFile.lastModified());
}
cacheSize.set(size);
cacheCount.set(count);
}
}
}).start();
}
private void put(File file) {
int curCacheCount = cacheCount.get();
while (curCacheCount + 1 > countLimit) {
long freedSize = removeNext();
cacheSize.addAndGet(-freedSize);
curCacheCount = cacheCount.addAndGet(-1);
}
cacheCount.addAndGet(1);
long valueSize = calculateSize(file);
long curCacheSize = cacheSize.get();
while (curCacheSize + valueSize > sizeLimit) {
long freedSize = removeNext();
curCacheSize = cacheSize.addAndGet(-freedSize);
}
cacheSize.addAndGet(valueSize);
Long currentTime = System.currentTimeMillis();
file.setLastModified(currentTime);
lastUsageDates.put(file, currentTime);
}
private File get(String key) {
File file = newFile(key);
Long currentTime = System.currentTimeMillis();
file.setLastModified(currentTime);
lastUsageDates.put(file, currentTime);
return file;
}
private File newFile(String key) {
return new File(cacheDir, key.hashCode() + "");
}
private boolean remove(String key) {
File image = get(key);
return image.delete();
}
private void clear() {
lastUsageDates.clear();
cacheSize.set(0);
File[] files = cacheDir.listFiles();
if (files != null) {
for (File f : files) {
f.delete();
}
}
}
/**
* 绉婚櫎鏃х殑鏂囦欢
*
* @return
*/
private long removeNext() {
if (lastUsageDates.isEmpty()) {
return 0;
}
Long oldestUsage = null;
File mostLongUsedFile = null;
Set<Entry<File, Long>> entries = lastUsageDates.entrySet();
synchronized (lastUsageDates) {
for (Entry<File, Long> entry : entries) {
if (mostLongUsedFile == null) {
mostLongUsedFile = entry.getKey();
oldestUsage = entry.getValue();
} else {
Long lastValueUsage = entry.getValue();
if (lastValueUsage < oldestUsage) {
oldestUsage = lastValueUsage;
mostLongUsedFile = entry.getKey();
}
}
}
}
long fileSize = calculateSize(mostLongUsedFile);
if (mostLongUsedFile.delete()) {
lastUsageDates.remove(mostLongUsedFile);
}
return fileSize;
}
private long calculateSize(File file) {
return file.length();
}
}
/**
* @title 鏃堕棿璁$畻宸ュ叿绫�
* @author 鏉ㄧ娴凤紙michael锛�www.yangfuhai.com
* @version 1.0
*/
private static class Utils {
/**
* 鍒ゆ柇缂撳瓨鐨凷tring鏁版嵁鏄惁鍒版湡
*
* @param str
* @return true锛氬埌鏈熶簡 false锛氳繕娌℃湁鍒版湡
*/
private static boolean isDue(String str) {
return isDue(str.getBytes());
}
/**
* 鍒ゆ柇缂撳瓨鐨刡yte鏁版嵁鏄惁鍒版湡
*
* @param data
* @return true锛氬埌鏈熶簡 false锛氳繕娌℃湁鍒版湡
*/
private static boolean isDue(byte[] data) {
String[] strs = getDateInfoFromDate(data);
if (strs != null && strs.length == 2) {
String saveTimeStr = strs[0];
while (saveTimeStr.startsWith("0")) {
saveTimeStr = saveTimeStr
.substring(1, saveTimeStr.length());
}
long saveTime = Long.valueOf(saveTimeStr);
long deleteAfter = Long.valueOf(strs[1]);
if (System.currentTimeMillis() > saveTime + deleteAfter * 1000) {
return true;
}
}
return false;
}
private static String newStringWithDateInfo(int second, String strInfo) {
return createDateInfo(second) + strInfo;
}
private static byte[] newByteArrayWithDateInfo(int second, byte[] data2) {
byte[] data1 = createDateInfo(second).getBytes();
byte[] retdata = new byte[data1.length + data2.length];
System.arraycopy(data1, 0, retdata, 0, data1.length);
System.arraycopy(data2, 0, retdata, data1.length, data2.length);
return retdata;
}
private static String clearDateInfo(String strInfo) {
if (strInfo != null && hasDateInfo(strInfo.getBytes())) {
strInfo = strInfo.substring(strInfo.indexOf(mSeparator) + 1,
strInfo.length());
}
return strInfo;
}
private static byte[] clearDateInfo(byte[] data) {
if (hasDateInfo(data)) {
return copyOfRange(data, indexOf(data, mSeparator) + 1,
data.length);
}
return data;
}
private static boolean hasDateInfo(byte[] data) {
return data != null && data.length > 15 && data[13] == '-'
&& indexOf(data, mSeparator) > 14;
}
private static String[] getDateInfoFromDate(byte[] data) {
if (hasDateInfo(data)) {
String saveDate = new String(copyOfRange(data, 0, 13));
String deleteAfter = new String(copyOfRange(data, 14,
indexOf(data, mSeparator)));
return new String[] { saveDate, deleteAfter };
}
return null;
}
private static int indexOf(byte[] data, char c) {
for (int i = 0; i < data.length; i++) {
if (data[i] == c) {
return i;
}
}
return -1;
}
private static byte[] copyOfRange(byte[] original, int from, int to) {
int newLength = to - from;
if (newLength < 0)
throw new IllegalArgumentException(from + " > " + to);
byte[] copy = new byte[newLength];
System.arraycopy(original, from, copy, 0,
Math.min(original.length - from, newLength));
return copy;
}
private static final char mSeparator = ' ';
private static String createDateInfo(int second) {
String currentTime = System.currentTimeMillis() + "";
while (currentTime.length() < 13) {
currentTime = "0" + currentTime;
}
return currentTime + "-" + second + mSeparator;
}
/*
* Bitmap 鈫�byte[]
*/
private static byte[] Bitmap2Bytes(Bitmap bm) {
if (bm == null) {
return null;
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
return baos.toByteArray();
}
/*
* byte[] 鈫�Bitmap
*/
private static Bitmap Bytes2Bimap(byte[] b) {
if (b.length == 0) {
return null;
}
return BitmapFactory.decodeByteArray(b, 0, b.length);
}
/*
* Drawable 鈫�Bitmap
*/
private static Bitmap drawable2Bitmap(Drawable drawable) {
if (drawable == null) {
return null;
}
// 鍙�drawable 鐨勯暱瀹�
int w = drawable.getIntrinsicWidth();
int h = drawable.getIntrinsicHeight();
// 鍙�drawable 鐨勯鑹叉牸寮�
Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
: Bitmap.Config.RGB_565;
// 寤虹珛瀵瑰簲 bitmap
Bitmap bitmap = Bitmap.createBitmap(w, h, config);
// 寤虹珛瀵瑰簲 bitmap 鐨勭敾甯�
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, w, h);
// 鎶�drawable 鍐呭鐢诲埌鐢诲竷涓�
drawable.draw(canvas);
return bitmap;
}
/*
* Bitmap 鈫�Drawable
*/
@SuppressWarnings("deprecation")
private static Drawable bitmap2Drawable(Bitmap bm) {
if (bm == null) {
return null;
}
return new BitmapDrawable(bm);
}
}
}
5.在写下如何缓存的例子吧:
/**
* 网络解析数据
*/
private void getHttp() {
// TODO Auto-generated method stub
HttpUtils httpUtils = new HttpUtils();
String path = Urls.Detail_URL;
// url 路径
// target 目标位置下到什么位置
// callback 回调
httpUtils.send(HttpMethod.GET, path, new RequestCallBack<String>() {
@Override
public void onFailure(HttpException arg0, String arg1) {
// TODO Auto-generated method stub
//读取(没有网的时候读取本地数据)
String asString = aCache.getAsString("result");
//判断本地有没有
if(!TextUtils.isEmpty(asString)){
Toast.makeText(getActivity(), "本地缓存", 0).show();
Gson gson = new Gson();
mData = gson.fromJson(asString, Data1.class);
datalist = mData.data.briefs;
hashMap = new HashMap<Integer, ArrayList<MyBriefs>>();
ArrayList<MyBriefs> briefs2 = new ArrayList<MyBriefs>();
ArrayList<MyBriefs> briefs3 = new ArrayList<MyBriefs>();
ArrayList<MyBriefs> briefs4 = new ArrayList<MyBriefs>();
for (int j = 0; j < datalist.size(); j++) {
if (j < 6) {
briefs2.add(datalist.get(j));
} else if (j < 12) {
briefs3.add(datalist.get(j));
} else {
briefs4.add(datalist.get(j));
}
}
hashMap.put(0, briefs2);
hashMap.put(1, briefs3);
hashMap.put(2, briefs4);
hashMap.put(3, briefs2);
hashMap.put(4, briefs3);
hashMap.put(5, briefs4);
handler.sendEmptyMessageDelayed(0, 3000);
//创建弹框,进行判断
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("网络提示!");
builder.setPositiveButton("设置网络", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
//跳转到系统设置界面
startActivity(new Intent(android.provider.Settings.ACTION_DATA_ROAMING_SETTINGS));
}
});
builder.setNegativeButton("不理会", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
builder.show();
}
}
@Override
public void onSuccess(ResponseInfo<String> arg0) {
// TODO Auto-generated method stub
String result = arg0.result;
//存储
aCache.put("result",result);
Toast.makeText(mActivity, "保存数据", 0).show();
// aCache.put(key, value, saveTime);//保存多长时间
Gson gson = new Gson();
mData = gson.fromJson(result, Data1.class);
datalist = mData.data.briefs;
hashMap = new HashMap<Integer, ArrayList<MyBriefs>>();
ArrayList<MyBriefs> briefs2 = new ArrayList<MyBriefs>();
ArrayList<MyBriefs> briefs3 = new ArrayList<MyBriefs>();
ArrayList<MyBriefs> briefs4 = new ArrayList<MyBriefs>();
for (int j = 0; j < datalist.size(); j++) {
if (j < 6) {
briefs2.add(datalist.get(j));
} else if (j < 12) {
briefs3.add(datalist.get(j));
} else {
briefs4.add(datalist.get(j));
}
}
hashMap.put(0, briefs2);
hashMap.put(1, briefs3);
hashMap.put(2, briefs4);
hashMap.put(3, briefs2);
hashMap.put(4, briefs3);
hashMap.put(5, briefs4);
handler.sendEmptyMessageDelayed(0, 3000);
// Home_ListView_Adapter home_GridView_Adapter = new
// Home_ListView_Adapter(
// getActivity(), images, hashMap);
// home_listView.setAdapter(home_GridView_Adapter);
// progressDialog.dismiss();
}
});
}
***读取本地缓存(已经缓存下来的数据):
//读取(没有网的时候读取本地数据)
String asString = aCache.getAsString("result");
***存储数据:
//存储
aCache.put("result",result);
*******************************希望对大家有帮助******************************