栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 移动开发 > Android

Android中图片的三级缓存机制

Android 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Android中图片的三级缓存机制

我们不能每次加载图片的时候都让用户从网络上下载,这样不仅浪费流量又会影响用户体验,所以Android中引入了图片的缓存这一操作机制。

原理:

  首先根据图片的网络地址在网络上下载图片,将图片先缓存到内存缓存中,缓存到强引用中 也就是LruCache中。如果强引用中空间不足,就会将较早存储的图片对象驱逐到软引用(softReference)中存储,然后将图片缓存到文件(内部存储外部存储)中;读取图片的时候,先读取内存缓存,判断强引用中是否存在图片,如果强引用中存在,则直接读取,如果强引用中不存在,则判断软引用中是否存在,如果软引用中存在,则将软引用中的图片添加到强引用中并且删除软引用中的数据,如果软引用中不存在,则读取文件存储,如果文件存储不存在,则网络加载。

  下载: 网络--内存--文件

  读取: 内存--强引用--软引用--文件--网络

也就是这样的一个过程,下面用一个简单地demo来演示一下图片你的三级缓存,此demo中只有一个界面,界面上一个ImageView用来显示图片,一个按钮用来点击的时候加载图片。布局如下:




  因为要从网络下载数据,还要存储到本地sd卡中,所以不要忘了为程序添加网络访问的权限、网络状态访问的权限和向外部存储设备写内容的权限:



  接着,创建一个 HttpUtils 工具类用于访问网络,代码如下:

package com.yztc.lx.cashimg;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpUtils {

public static boolean isNetConn(Context mContext) {
ConnectivityManager manager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = manager.getActiveNetworkInfo();
if (info != null) {
return info.isConnected();
} else {
return false;
}
}

public static byte[] getDateFromNet(String path) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
conn.setDoInput(true);
conn.connect();
if (conn.getResponseCode()==200) {
InputStream is = conn.getInputStream();
byte b[] = new byte[1024];
int len;
while ((len=is.read(b))!=-1) {
baos.write(b, 0, len);
}
return baos.toByteArray();
}
} catch (IOException e) {
e.printStackTrace();
}
return baos.toByteArray();
}
}

  还有操作外部存储的工具类:

package com.yztc.lx.cashimg;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class ExternalStorageUtils {

public static boolean storeToSDRoot(String imgName, byte buff[]) {
boolean b = false;
String basePath = Environment.getExternalStorageDirectory().getAbsolutePath();
File file = new File(basePath, imgName);
try {
FileOutputStream fos = new FileOutputStream(file);
fos.write(buff);
fos.close();
b = true;
} catch (IOException e) {
e.printStackTrace();
}
return b;
}

public static Bitmap getImgFromSDRoot(String imgName) {
Bitmap bitmap = null;
String basePath = Environment.getExternalStorageDirectory().getAbsolutePath();
File file = new File(basePath, imgName);
try {
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte b[] = new byte[1024];
int len;
while ((len = fis.read(b)) != -1) {
baos.write(b, 0, len);
}
byte buff[] = baos.toByteArray();
if (buff != null && buff.length != 0) {
bitmap = BitmapFactory.decodeByteArray(buff, 0, buff.length);
}
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
}

  本例中将图片默认存在了sd卡根目录中。

  然后是最主要的主函数了:

package com.yztc.lx.cashimg;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.LruCache;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import java.lang.ref.SoftReference;
import java.util.linkedHashMap;
public class MainActivity extends AppCompatActivity implements View.onClickListener {
private Button btn_download;
private ImageView iv_img;
private MyLruCache myLruCache;
private linkedHashMap> cashMap = new linkedHashMap<>();
private static final String TAG = "MainActivity";
private String imgPath = "http://www.3dmgame.com/UploadFiles/201212/Medium_20121217143424221.jpg";
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
Bitmap bitmap = (Bitmap) msg.obj;
iv_img.setImageBitmap(bitmap);
Toast.makeText(MainActivity.this, "从网络上下载图片", Toast.LENGTH_SHORT).show();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
int totalMemory = (int) Runtime.getRuntime().maxMemory();
int size = totalMemory / 8;
myLruCache = new MyLruCache(size);
btn_download.setonClickListener(this);
}
private void initView() {
btn_download = (Button) findViewById(R.id.btn_download);
iv_img = (ImageView) findViewById(R.id.iv_img);
}
@Override
public void onClick(View v) {
Bitmap b = getImgCache();
if (b != null) {
iv_img.setImageBitmap(b);
} else {
new Thread(new Runnable() {
@Override
public void run() {
if (HttpUtils.isNetConn(MainActivity.this)) {
byte b[] = HttpUtils.getDateFromNet(imgPath);
if (b != null && b.length != 0) {
Bitmap bitmap = BitmapFactory.decodeByteArray(b, 0, b.length);
Message msg = Message.obtain();
msg.obj = bitmap;
handler.sendMessage(msg);
myLruCache.put(imgPath, bitmap);
Log.d(TAG, "run: " + "缓存到强引用中成功");
boolean bl = ExternalStorageUtils.storeToSDRoot("haha.jpg", b);
if (bl) {
Log.d(TAG, "run: " + "缓存到本地内存成功");
} else {
Log.d(TAG, "run: " + "缓存到本地内存失败");
}
} else {
Toast.makeText(MainActivity.this, "下载失败!", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(MainActivity.this, "请检查你的网络!", Toast.LENGTH_SHORT).show();
}
}
}).start();
}
}

public Bitmap getImgCache() {
Bitmap bitmap = myLruCache.get(imgPath);
if (bitmap != null) {
Log.d(TAG, "getImgCache: " + "从LruCache获取图片");
} else {
SoftReference sr = cashMap.get(imgPath);
if (sr != null) {
bitmap = sr.get();
myLruCache.put(imgPath, bitmap);
cashMap.remove(imgPath);
Log.d(TAG, "getImgCache: " + "从软引用获取图片");
} else {
bitmap = ExternalStorageUtils.getImgFromSDRoot("haha.jpg");
Log.d(TAG, "getImgCache: " + "从外部存储获取图片");
}
}
return bitmap;
}

public class MyLruCache extends LruCache {

public MyLruCache(int maxSize) {
super(maxSize);
}
//返回每个图片的大小
@Override
protected int sizeOf(String key, Bitmap value) {
//获取当前变量每行的字节数和行高度(基本是固定写法,记不住给我背!)
return value.getRowBytes() * value.getHeight();
}

@Override
protected void entryRemoved(boolean evicted, String key, Bitmap oldValue, Bitmap newValue) {
if (evicted) {

SoftReference softReference = new SoftReference(oldValue);
cashMap.put(key, softReference);
}
}
}
}

  基本的思路都在代码注释中写的很详细了,主要就是要自定义一个类,来继承系统的LruCache,实现其中的两个主要的方法sizeOf()和entryRemoved(),还有就是必须重写它的构造函数。

以上所述是小编给大家介绍的Android中图片的三级缓存机制的全部叙述,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的,在此也非常感谢大家对考高分网网站的支持!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/161724.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号