这里说的三级缓存,分别指的是:内存缓存、文件缓存和网络这三个层面。
一般来说,我们首次加载图片,内存和文件是没有缓存的,这样我们需要从网络加载,加载完成后,我们会存到内存和文件中去;当再次加载图片的时候,我们会先查找内存有没有,如果有就直接显示内存中的图片,如果没有,我们会接着查找文件中是否有,如果文件中有,我们会显示文件中的图片,并且把它存到内存中去,这样下次我们在内存中就能找到它了。
我们之所以要做缓存,主要是为了提高效率,节省流量。但是为什么要做三级呢?为什么不只存在内存或者只存在文件中呢?这是因为内存的读取速度快,但是容易被回收,容量小,文件的读取速度次之,不过容量大,不到不得已不会被回收。
//权限
<uses-permission android:name="android.permission.INTERNET"></uses-permission> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
/** * author:Created by WangZhiQiang on 2017-09-04. * 处理三级缓存 * 内存缓存(LruCache-->最近最少使用算法,当缓存慢的时候,自动把最近使用最少的删除,腾出来的空间添加新的缓存内容) * sd卡缓存 * 网络 *///工具类 public class ImagesUtils { Handler handler; private final File cacheDir; private final ExecutorService newFixedThreadPool; private final LruCache<String, Bitmap> lruCache; //有参构造 public ImagesUtils (Context context, Handler handler){ this.handler = handler; //获得你手机上的最大内存 long maxMemory = Runtime.getRuntime().maxMemory(); int maxSize = (int) (maxMemory / 8); //得到本app在sd上的缓存文件夹 cacheDir = context.getCacheDir(); // 初始化线程池;初始化5个现成,供程序使用 newFixedThreadPool = Executors.newFixedThreadPool(5); lruCache = new LruCache<String, Bitmap>(maxSize) { //每次缓存图片都要调用这个方法; @Override protected int sizeOf(String key, Bitmap value) { return value.getRowBytes()*value.getHeight(); } }; } /** * 取图片, * * @param path * @return */ public Bitmap getBitMap(String path){ //获取内存中的图片 Bitmap bitmap = lruCache.get(path); if(bitmap!=null){ System.out.println("我走了内存"); return bitmap; } //从本地去取,sd卡去取bitmap bitmap = getBitMapFromLocal(path); if(bitmap!=null){ System.out.println("我走了本地缓存"); return bitmap; } // 从网络去取 getBitmapFromNet(path); return null; } /** * 从网络 * * @param path */ private void getBitmapFromNet(final String path) { //用线程池里的线程执行请求网络操作; newFixedThreadPool.execute(new Runnable() { @Override public void run() { try { URL url=new URL(path); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); int code = connection.getResponseCode(); if(code==200){ InputStream inputStream = connection.getInputStream(); Bitmap bitmap = BitmapFactory.decodeStream(inputStream); Message msg = new Message(); msg.what = 111; msg.obj = bitmap; Bundle data = new Bundle(); data.putString("tag", path); msg.setData(data); handler.sendMessage(msg); //缓存到本地 saveBitmapToLocal(bitmap, path); //缓存到内存 lruCache.put(path, bitmap); } } catch (Exception e) { e.printStackTrace(); } } }); } protected void saveBitmapToLocal(Bitmap bitmap, String path) { try { String encode = EncoderUtils.encode(path); FileOutputStream fileOutputStream = new FileOutputStream(cacheDir + "/" + encode); //图片二次裁剪 bitmap.compress(Bitmap.CompressFormat.JPEG, 80, fileOutputStream); } catch (Exception e) { e.printStackTrace(); } } private Bitmap getBitMapFromLocal(String path) { try { String encode = EncoderUtils.encode(path); FileInputStream fileInputStream = new FileInputStream(cacheDir + "/" + encode); Bitmap bitmap = BitmapFactory.decodeStream(fileInputStream); //存到内存 lruCache.put(path, bitmap); return bitmap; } catch (Exception e) { e.printStackTrace(); } return null; } }
/** * author:Created by WangZhiQiang on 2017-09-04. * 工具类,把对url进行md5加密,加密后以字符串的形式返回; * 缓存的时候用key(url加密后的字符串)对应value(bitmap) */ public class EncoderUtils { /** * Md5Encoder * * @param string * @return * @throws Exception */ public static String encode(String string) throws Exception { byte[] hash = MessageDigest.getInstance("MD5").digest( string.getBytes("UTF-8")); StringBuilder hex = new StringBuilder(hash.length * 2); for (byte b : hash) { if ((b & 0xFF) < 0x10) { hex.append("0"); } hex.append(Integer.toHexString(b & 0xFF)); } return hex.toString(); } }
public class MainActivity extends AppCompatActivity { private GridView gv; String[] imageUrls = new String[] { "https://img-my.csdn.net/uploads/201407/26/1406383299_1976.jpg", "https://img-my.csdn.net/uploads/201407/26/1406383299_1976.jpg", "https://img-my.csdn.net/uploads/201407/26/1406383299_1976.jpg", "https://img-my.csdn.net/uploads/201407/26/1406383299_1976.jpg", "https://img-my.csdn.net/uploads/201407/26/1406383299_1976.jpg", "https://img-my.csdn.net/uploads/201407/26/1406383299_1976.jpg", "https://img-my.csdn.net/uploads/201407/26/1406383299_1976.jpg", "https://img-my.csdn.net/uploads/201407/26/1406383299_1976.jpg", "https://img-my.csdn.net/uplds/201407/26/1406383299_1976.jpg", "https://img-my.csdn.net/uploads/201407/26/1406383299_1976.jpg", "https://img-my.csdn.net/uploads/201407/26/1406383299_1976.jpg", "https://img-my.csdn.net/uploads/201407/26/1406383299_1976.jpg", "https://img-my.csdn.net/uploads/201407/26/1406383299_1976.jpg", "https://img-my.csdn.net/uploads/201407/26/1406383299_1976.jpg", "https://img-my.csdn.net/uploads/201407/26/1406383299_1976.jpg", "https://img-my.csdn.net/uploads/201407/26/1406383299_1976.jpg", "https://img-my.csdn.net/uploads/201407/26/1406383299_1976.jpg", "https://img-my.csdn.net/uploads/201407/26/1406383299_1976.jpg", "https://img-my.csdn.net/uploads/201407/26/1406383299_1976.jpg", "https://img-my.csdn.net/uploads/201407/26/1406383299_1976.jpg", "https://img-my.csdn.net/uploads/201407/26/1406383299_1976.jpg", "https://img-my.csdn.net/uploads/201407/26/1406383299_1976.jpg", "https://img-my.csdn.net/uploads/201407/26/1406383299_1976.jpg", "https://img-my.csdn.net/uploads/201407/26/1406383291_6518.jpg", "https://img-my.csdn.net/uploads/201407/26/1406383291_8239.jpg", "https://img-my.csdn.net/uploads/201407/26/1406383290_9329.jpg", "https://img-my.csdn.net/uploads/201407/26/1406383290_1042.jpg", "https://img-my.csdn.net/uploads/201407/26/1406383275_3977.jpg", "https://img-my.csdn.net/uploads/201407/26/1406383265_8550.jpg", "https://img-my.csdn.net/uploads/201407/26/1406383264_3954.jpg", "https://img-my.csdn.net/uploads/201407/26/1406383264_4787.jpg", }; Handler handler=new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); } }; private ImagesUtils imagesutils; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); imagesutils = new ImagesUtils(this,handler); gv = (GridView) findViewById(R.id.gv); gv.setAdapter(new myadaper()); } class myadaper extends BaseAdapter{ @Override public int getCount() { return imageUrls.length; } @Override public Object getItem(int i) { return null; } @Override public long getItemId(int i) { return 0; } @Override public View getView(int i, View view, ViewGroup viewGroup) { ImageView iv = new ImageView(MainActivity.this); iv.setTag(imageUrls[i]); //取图片 Bitmap bitmap = imagesutils.getBitMap(imageUrls[i]); // 从内存中或者缓存中 if(bitmap !=null){ iv.setImageBitmap(bitmap); } // 获取图片 return iv; } } }