//第一种方式:
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
//获取当前硬件条件下应用所占的大致内存大小,单位为M
int memorySize = manager.getMemoryClass();//M
int cacheSize = memorySize/ 8;
//第二种方式(比较常用)
int memorySize = (int) Runtime.getRuntime().maxMemory();//bytes
int cacheSize = memorySize / 8;
//初始化 LruCache 且设置了缓存大小
LruCache<String,Bitmap> lruCache = new LruCache<String,Bitmap>(cacheSize){
@Override
protected int sizeOf(String key,Bitmap value) {
//计算每一个缓存Bitmap的所占内存的大小,内存单位应该和 cacheSize 的单位保持一致
return value.getByteCount();
}
};
//参数put(String key,Bitmap bitmap)
lruCache.put(key,bitmap)
//参数get(String key)
Bitmap bitmap = lruCache.get(key);
imageView.setImageBitmap(bitmap);
//ImageLoader
public class ImageLoader {
private LruCache<String,Bitmap> lruCache;
public ImageLoader() {
int memorySize = (int) Runtime.getRuntime().maxMemory() / 1024;
int cacheSize = memorySize / 8;
lruCache = new LruCache<String,Bitmap>(cacheSize){
@Override
protected int sizeOf(String key,Bitmap value) {
//计算每一个缓存Bitmap的所占内存的大小
return value.getByteCount()/1024;
}
};
}
/**
* 添加Bitmapd到LruCache中
* @param key
* @param bitmap
*/
public void addBitmapToLruCache(String key,Bitmap bitmap){
if (getBitmapFromLruCache(key)==null){
lruCache.put(key,bitmap);
}
}
/**
* 获取缓存的Bitmap
* @param key
*/
public Bitmap getBitmapFromLruCache(String key){
if (key!=null){
return lruCache.get(key);
}
return null;
}
/**
* 移出缓存
* @param key
*/
public void removeBitmapFromLruCache(String key){
if (key!=null){
lruCache.remove(key);
}
}
}
//加载图片的线程
public class LoadImageThread extends Thread {
private Activity mActivity;
private String mImageUrl;
private ImageLoader mImageLoader;
private ImageView mImageView;
public LoadImageThread(Activity activity,ImageLoader imageLoader,ImageView imageView,String imageUrl) {
this.mActivity = activity;
this.mImageLoader = imageLoader;
this.mImageView = imageView;
this.mImageUrl = imageUrl;
}
@Override
public void run() {
HttpURLConnection connection = null;
InputStream is = null;
try {
URL url = new URL(mImageUrl);
connection = (HttpURLConnection) url.openConnection();
is = connection.getInputStream();
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK){
final Bitmap bitmap = BitmapFactory.decodeStream(is);
mImageLoader.addBitmapToLruCache("bitmap",bitmap);
mActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
mImageView.setImageBitmap(bitmap);
}
});
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection!=null){
connection.disconnect();
}
if (is!=null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
//获取图片
private void loadImage(){
Bitmap bitmap = imageLoader.getBitmapFromLruCache("bitmap");
if (bitmap==null){
Log.i(TAG,"从网络获取图片");
new LoadImageThread(this,imageLoader,imageView,url).start();
}else{
Log.i(TAG,"从缓存中获取图片");
imageView.setImageBitmap(bitmap);
}
}
// 移出缓存
private void removeBitmapFromL(String key){
imageLoader.removeBitmapFromLruCache(key);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btnLoadLruCache:
loadImage();
break;
case R.id.btnRemoveBitmapL:
removeBitmapFromL("bitmap");
break;
}
}
/**
* 返回相应目录中的缓存,如果不存在则创建
* @param directory 缓存目录
* @param appVersion 表示应用的版本号,一般设为1
* @param valueCount 每个Key所对应的Value的数量,一般设为1
* @param maxSize 缓存大小
* @throws IOException if reading or writing the cache directory fails
*/
public static DiskLruCache open(File directory,int appVersion,int valueCount,long maxSize)
throws IOException {
...
// 创建DiskLruCache
DiskLruCache cache = new DiskLruCache(directory,appVersion,valueCount,maxSize);
if (cache.journalFile.exists()) {
...
return cache;
}
//如果缓存目录不存在,创建缓存目录以及DiskLruCache
directory.mkdirs();
cache = new DiskLruCache(directory,maxSize);
...
return cache;
}
//计算url的MD5值作为key
private String hashKeyForDisk(String url) {
String cacheKey;
try {
final MessageDigest mDigest = MessageDigest.getInstance("MD5");
mDigest.update(url.getBytes());
cacheKey = bytesToHexString(mDigest.digest());
} catch (NoSuchAlgorithmException e) {
cacheKey = String.valueOf(url.hashCode());
}
return cacheKey;
}
private String bytesToHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
String hex = Integer.toHexString(0xFF & bytes[i]);
if (hex.length() == 1) {
sb.append('0');
}
sb.append(hex);
}
return sb.toString();
}
//添加网络图片到内存缓存和磁盘缓存
public void putCache(final String url,final CallBack callBack){
Log.i(TAG,"putCache...");
new AsyncTask<String,Void,Bitmap>(){
@Override
protected Bitmap doInBackground(String... params) {
String key = hashKeyForDisk(params[0]);
DiskLruCache.Editor editor = null;
Bitmap bitmap = null;
try {
URL url = new URL(params[0]);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(1000 * 30);
conn.setConnectTimeout(1000 * 30);
ByteArrayOutputStream baos = null;
if(conn.getResponseCode()==HttpURLConnection.HTTP_OK){
BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
baos = new ByteArrayOutputStream();
byte[] bytes = new byte[1024];
int len = -1;
while((len=bis.read(bytes))!=-1){
baos.write(bytes,len);
}
bis.close();
baos.close();
conn.disconnect();
}
if (baos!=null){
bitmap = decodeSampledBitmapFromStream(baos.toByteArray(),300,200);
addBitmapToCache(params[0],bitmap);//添加到内存缓存
editor = diskLruCache.edit(key);
//关键
bitmap.compress(Bitmap.CompressFormat.JPEG,100,editor.newOutputStream(0));
editor.commit();//提交
}
} catch (IOException e) {
try {
editor.abort();//放弃写入
} catch (IOException e1) {
e1.printStackTrace();
}
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
callBack.response(bitmap);
}
}.execute(url);
}
//获取磁盘缓存
public InputStream getDiskCache(String url) {
Log.i(TAG,"getDiskCache...");
String key = hashKeyForDisk(url);
try {
DiskLruCache.Snapshot snapshot = diskLruCache.get(key);
if (snapshot!=null){
return snapshot.getInputStream(0);
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
//MainActivity.java
public class MainActivity extends AppCompatActivity {
private static final String TAG = "cache_test";
public static String CACHE_DIR = "diskCache"; //缓存目录
public static int CACHE_SIZE = 1024 * 1024 * 10; //缓存大小
private ImageView imageView;
private LruCache<String,String> lruCache;
private LruCacheUtils cacheUtils;
private String url = "http://img06.tooopen.com/images/20161012/tooopen_sy_181713275376.jpg";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imageView);
}
@Override
protected void onResume() {
super.onResume();
cacheUtils = LruCacheUtils.getInstance();
//创建内存缓存和磁盘缓存
cacheUtils.createCache(this,CACHE_DIR,CACHE_SIZE);
}
@Override
protected void onPause() {
super.onPause();
cacheUtils.flush();
}
@Override
protected void onStop() {
super.onStop();
cacheUtils.close();
}
public void loadImage(View view){
load(url,imageView);
}
public void removeLruCache(View view){
Log.i(TAG,"移出内存缓存...");
cacheUtils.removeLruCache(url);
}
public void removeDiskLruCache(View view){
Log.i(TAG,"移出磁盘缓存...");
cacheUtils.removeDiskLruCache(url);
}
private void load(String url,final ImageView imageView){
//从内存中获取图片
Bitmap bitmap = cacheUtils.getBitmapFromCache(url);
if (bitmap == null){
//从磁盘中获取图片
InputStream is = cacheUtils.getDiskCache(url);
if (is == null){
//从网络上获取图片
cacheUtils.putCache(url,new LruCacheUtils.CallBack<Bitmap>() {
@Override
public void response(Bitmap bitmap1) {
Log.i(TAG,"从网络中获取图片...");
Log.i(TAG,"正在从网络中下载图片...");
imageView.setImageBitmap(bitmap1);
Log.i(TAG,"从网络中获取图片成功...");
}
});
}else{
Log.i(TAG,"从磁盘中获取图片...");
bitmap = BitmapFactory.decodeStream(is);
imageView.setImageBitmap(bitmap);
}
}else{
Log.i(TAG,"从内存中获取图片...");
imageView.setImageBitmap(bitmap);
}
}
}
本站采用系统自动发货方式,付款后即出现下载入口,如有疑问请咨询在线客服!
售后时间:早10点 - 晚11:30点Copyright © 2024 jiecseo.com All rights reserved. 粤ICP备18085929号
欢迎光临【捷杰建站】,本站所有资源仅供学习与参考,禁止用于商业用途或从事违法行为!
技术营运:深圳市晟艺互动传媒有限公司