缓存工具类
public class LruUtils {
private LruCache<String, Bitmap> lruCache;
public LruUtils(){
int l = (int)Runtime.getRuntime().maxMemory();
lruCache=new LruCache<String,Bitmap>(l/8){
@Override
protected int sizeOf(String key, Bitmap value) {
return value.getByteCount();
}
};
}
public Bitmap get(String k){
return lruCache.get(k);
}
public void set(String k,Bitmap v){
lruCache.put(k,v);
}
}
SD卡读取工具类
public class SDcard {
private static SDcard sDcard=new SDcard();
private SDcard(){
}
public static SDcard getInstance(){
return sDcard;
}
public static void setBitmap(String name, Bitmap bitmap) throws FileNotFoundException {
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
File file=Environment.getExternalStorageDirectory();
File file1=new File(file,name);
bitmap.compress(Bitmap.CompressFormat.JPEG,100,new FileOutputStream(file1));
}
}
public static Bitmap getBitmap(String name){
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
File file=Environment.getExternalStorageDirectory();
File file1=new File(file,name);
return BitmapFactory.decodeFile(file1.getAbsolutePath());
}
return null;
}
}
网络下载图片类
public class Workthread extends AsyncTask<String,Void, Bitmap> {
public static Bitmap getBitmap(String url) throws ExecutionException, InterruptedException {
return new Workthread().execute(url).get();
}
@Override
protected Bitmap doInBackground(String... strings) {
try {
URL url=new URL(strings[0]);
HttpURLConnection http = (HttpURLConnection) url.openConnection();
http.setConnectTimeout(5000);
http.setRequestMethod("GET");
http.connect();
if(http.getResponseCode()==200){
InputStream is = http.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(is);
return bitmap;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
Main
public void click() throws Exception {
Bitmap bitmap = lruUtils.get("aaa");
if(bitmap!=null){
imageView.setImageBitmap(bitmap);
Toast.makeText(this,"图片来自内存",Toast.LENGTH_SHORT).show();
}else{
Bitmap bitmap1 = SDcard.getBitmap("aaa.jpg");
if(bitmap1!=null){
imageView.setImageBitmap(bitmap1);
Toast.makeText(this,"图片来自sd卡",Toast.LENGTH_SHORT).show();
lruUtils.set("aaa",bitmap1);
}else{
Bitmap bitmap2 = Workthread.getBitmap("http://www.qubaobei.com/ios/cf/uploadfile/132/9/8289.jpg");
if(bitmap2!=null){
imageView.setImageBitmap(bitmap2);
Toast.makeText(this,"图片来自网络",Toast.LENGTH_SHORT).show();
SDcard.setBitmap("aaa.jpg",bitmap2);
lruUtils.set("aaa",bitmap2);
}else{
Toast.makeText(this,"查无此图片",Toast.LENGTH_SHORT).show();
}
}
}
}
效果图