您的位置:首页 > 移动开发 > Android开发

Android 开发之自定义三级缓存

2015-12-07 00:00 501 查看
以下内容为视频学习的记录内容step1:网络缓存NetCacheUtils
package com.zaizai.smartcity.utils.bitmap;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;

/**
* 网络缓存
*/
public class NetCacheUtils {

private LocalCacheUtils mLocalCacheUtils;
private MemoryCacheUtils mMemoryCacheUtils;
private Handler handler;

public NetCacheUtils(LocalCacheUtils localCacheUtils,
MemoryCacheUtils memoryCacheUtils) {
mLocalCacheUtils = localCacheUtils;
mMemoryCacheUtils = memoryCacheUtils;
}

/**
* 从网络下载图片
*
* @param ivPicture
* @param url
*/
public void getBitmapFromNet(ImageView ivPicture, String url) {
new BitmapTask().execute(ivPicture, url);// 启动AsyncTask,
handler = new Handler() {
@Override
public void handleMessage(Message msg) {
Object[] objects = (Object[]) msg.obj;
ImageView imageView = (ImageView) objects[0];
String mUrl = (String) objects[1];
imageView.setTag(mUrl);
}
};
// 参数会在doInbackground中获取
}

/**
* Handler和线程池的封装
* <p/>
* 第一个泛型: 参数类型
* 第二个泛型: 更新进度的泛型,
* 第三个泛型是onPostExecute的返回结果
*/
class BitmapTask extends AsyncTask<Object, Void, Bitmap> {

private ImageView ivPicture;
private String url;
private Object[] objects;
private Message message;

/**
* 后台耗时方法在此执行, 子线程
*/
@Override

3ff0
protected Bitmap doInBackground(Object... params) {
ivPicture = (ImageView) params[0];
url = (String) params[1];

message = handler.obtainMessage();
objects = new Object[]{ivPicture, url
};
message.obj = objects;
handler.sendMessage(message);

return downloadBitmap(url);
}

/**
* 更新进度, 主线程
*/
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}

/**
* 耗时方法结束后,执行该方法, 主线程
*/
@Override
protected void onPostExecute(Bitmap result) {
if (result != null) {
String bindUrl = (String) ivPicture.getTag();

if (url.equals(bindUrl)) {// 确保图片设定给了正确的imageview
ivPicture.setImageBitmap(result);
mLocalCacheUtils.setBitmapToLocal(url, result);// 将图片保存在本地
mMemoryCacheUtils.setBitmapToMemory(url, result);// 将图片保存在内存
System.out.println("从网络缓存读取图片啦...");
}
}
}
}

/**
* 下载图片
*
* @param url
* @return
*/
private Bitmap downloadBitmap(String url) {

HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) new URL(url).openConnection();

conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
conn.setRequestMethod("GET");
conn.connect();

int responseCode = conn.getResponseCode();
if (responseCode == 200) {
InputStream inputStream = conn.getInputStream();

//图片压缩处理
BitmapFactory.Options option = new BitmapFactory.Options();
// option.inSampleSize = 2;//宽高都压缩为原来的二分之一, 此参数需要根据图片要展示的大小来确定
option.inPreferredConfig = Bitmap.Config.RGB_565;//设置图片格式

Bitmap bitmap = BitmapFactory.decodeStream(inputStream, null, option);
return bitmap;
}

} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
}
}

return null;
}

}
step2:本地缓存LocalCacheUtils
package com.zaizai.smartcity.utils.bitmap;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Environment;

import com.zaizai.smartcity.utils.MD5Encoder;

/**
* 本地缓存
*
*
*/
public class LocalCacheUtils {

public static final String CACHE_PATH = Environment
.getExternalStorageDirectory().getAbsolutePath() + "/smartcity_cache";

/**
* 从本地sdcard读图片
*/
public Bitmap getBitmapFromLocal(String url) {
try {
String fileName = MD5Encoder.encode(url);
File file = new File(CACHE_PATH, fileName);

if (file.exists()) {
Bitmap bitmap = BitmapFactory.decodeStream(new FileInputStream(
file));
return bitmap;
}

} catch (Exception e) {
e.printStackTrace();
}

return null;
}

/**
* 向sdcard写图片
*
* @param url
* @param bitmap
*/
public void setBitmapToLocal(String url, Bitmap bitmap) {
try {
String fileName = MD5Encoder.encode(url);

File file = new File(CACHE_PATH, fileName);

File parentFile = file.getParentFile();
if (!parentFile.exists()) {// 如果文件夹不存在, 创建文件夹
parentFile.mkdirs();
}

// 将图片保存在本地
bitmap.compress(CompressFormat.JPEG, 100,
new FileOutputStream(file));
} catch (Exception e) {
e.printStackTrace();
}

}
}
setp3:内存缓存
package com.zaizai.smartcity.utils.bitmap;

import android.graphics.Bitmap;
import android.support.v4.util.LruCache;

/**
* 内存缓存
*
*
*/
public class MemoryCacheUtils {

// private HashMap<String, SoftReference<Bitmap>> mMemoryCache = new
// HashMap<String, SoftReference<Bitmap>>();
private LruCache<String, Bitmap> mMemoryCache;

public MemoryCacheUtils() {
long maxMemory = Runtime.getRuntime().maxMemory() / 8;// 模拟器默认是16M
mMemoryCache = new LruCache<String, Bitmap>((int) maxMemory) {
@Override
protected int sizeOf(String key, Bitmap value) {
int byteCount = value.getRowBytes() * value.getHeight();// 获取图片占用内存大小
return byteCount;
}
};
}

/**
* 从内存读
*
* @param url
*/
public Bitmap getBitmapFromMemory(String url) {
// SoftReference<Bitmap> softReference = mMemoryCache.get(url);
// if (softReference != null) {
// Bitmap bitmap = softReference.get();
// return bitmap;
// }
return mMemoryCache.get(url);
}

/**
* 写内存
*
* @param url
* @param bitmap
*/
public void setBitmapToMemory(String url, Bitmap bitmap) {
// SoftReference<Bitmap> softReference = new
// SoftReference<Bitmap>(bitmap);
// mMemoryCache.put(url, softReference);
mMemoryCache.put(url, bitmap);
}
}
step4:自定义工具类
package com.zaizai.smartcity.utils.bitmap;

import android.graphics.Bitmap;
import android.widget.ImageView;

import com.zaizai.smartcity.R;

/**
* 自定义图片加载工具
*/
public class MyBitmapUtils {

NetCacheUtils mNetCacheUtils;
LocalCacheUtils mLocalCacheUtils;
MemoryCacheUtils mMemoryCacheUtils;

public MyBitmapUtils() {
mMemoryCacheUtils = new MemoryCacheUtils();
mLocalCacheUtils = new LocalCacheUtils();
mNetCacheUtils = new NetCacheUtils(mLocalCacheUtils, mMemoryCacheUtils);
}

public void display(ImageView ivPicture, String url) {
ivPicture.setImageResource(R.drawable.news_pic_default);// 设置默认加载图片

Bitmap bitmap = null;
// 从内存读
bitmap = mMemoryCacheUtils.getBitmapFromMemory(url);
if (bitmap != null) {
ivPicture.setImageBitmap(bitmap);
System.out.println("从内存读取图片啦...");
return;
}

// 从本地读
bitmap = mLocalCacheUtils.getBitmapFromLocal(url);
if (bitmap != null) {
ivPicture.setImageBitmap(bitmap);
System.out.println("从本地读取图片啦...");
mMemoryCacheUtils.setBitmapToMemory(url, bitmap);// 将图片保存在内存
return;
}
// 从网络读
mNetCacheUtils.getBitmapFromNet(ivPicture, url);
}

}

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Android studio