一个简单的demo, 里面的工具类简单的实现了三级缓存,使用异步请求AsyncTask请求图片,非喜勿喷
import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.os.Environment; import android.widget.ImageView; import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.lang.ref.SoftReference; import java.net.HttpURLConnection; import java.net.URL; import java.util.HashMap; public class Utils { private String imgUrl; private ImageView imageView; private HashMap<String,SoftReference<Bitmap>> hashMap=new HashMap<>(); public Utils(String imgUrl, ImageView imageView) { this.imgUrl = imgUrl; this.imageView = imageView; } public void execute() { //获取内存 if (getCacheInMemary(imgUrl)!=null){ imageView.setImageBitmap(getCacheInMemary(imgUrl)); System.out.println("1"); }else //获取磁盘 if (getcacheInDisc(imgUrl)!=null){ imageView.setImageBitmap(getcacheInDisc(imgUrl)); System.out.println("2"); }else { //获取网络 new MyAsyncTask().execute(imgUrl); System.out.println("3"); } } private Bitmap getCacheInMemary(String imgUrl) { SoftReference<Bitmap> bitmapSoftReference = hashMap.get(imgUrl); if (bitmapSoftReference!=null) { Bitmap bitmap = bitmapSoftReference.get(); return bitmap; } return null; } private Bitmap getcacheInDisc(String imgUrl) { try { File file=new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/me/"+new Md5FileNameGenerator().generate(imgUrl)); FileInputStream fileInputStream=new FileInputStream(file); return BitmapFactory.decodeStream(fileInputStream); } catch (Exception e) { e.printStackTrace(); } return null; } class MyAsyncTask extends AsyncTask<String,Integer,Bitmap> { @Override protected Bitmap doInBackground(String... strings) { try { URL url=new URL(strings[0]); HttpURLConnection connection= (HttpURLConnection) url.openConnection(); connection.connect(); if (connection.getResponseCode()==HttpURLConnection.HTTP_OK) { return BitmapFactory.decodeStream(connection.getInputStream()); } } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Bitmap bitmap) { imageView.setImageBitmap(bitmap); keepInMemary(bitmap); keepInDisc(bitmap); } } private void keepInMemary(Bitmap bitmap) { SoftReference<Bitmap> bitmapSoftReference=new SoftReference<Bitmap>(bitmap); hashMap.put(new Md5FileNameGenerator().generate(imgUrl),bitmapSoftReference); } private void keepInDisc(Bitmap bitmap) { try { File file=new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/me"); if (!file.exists()){ file.mkdirs(); } File file1=new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/me/"+new Md5FileNameGenerator().generate(imgUrl)); FileOutputStream fileOutputStream=new FileOutputStream(file1); bitmap.compress(Bitmap.CompressFormat.JPEG,100,fileOutputStream); } catch (FileNotFoundException e) { e.printStackTrace(); } } }