Because the project cannot use third parties at present, it can only create a third-level cache. The third-level cache is divided into memory cache, local cache, and network cache; the cache steps are network, memory, local, and then the order of the withdrawal is memory, local, and network. When citing images when loading images, try to use weak references as much as possible to avoid excessive images from producing OOM.
1. Memory cache, android provides us with LruCache=, which maintains a LinkedHashMap. LruCache can be used to store various types of data. We set its size, which is generally 1/8 of the maximum storage space of the system.
public class MemoryCacheUtil { private LruCache<String, Bitmap> lruCache; public MemoryCacheUtil(){ int maxSize = (int) (().maxMemory()/8); // Generally, 1/8 of the maximum memory of the current application is obtained as the capacity of LruCache lruCache = new LruCache<String, Bitmap>(maxSize){ // Set the size of the currently added image @Override protected int sizeOf(String key, Bitmap value) { return ()*(); } }; } // Get pictures from memory cache public Bitmap getBitmap(String url){ return (url); } //Save pictures in memory cache public void putBitmap(String url,Bitmap bitmap){ (url, bitmap); } }
2. The local cache obtains local files based on the url, encrypts the url with md5 as the file name to ensure the correctness of the file.
MD5 encryption tool class
public class MD5Encoder { public static String encode(String string) throws Exception { byte[] hash = ("MD5").digest(("UTF-8")); StringBuilder hex = new StringBuilder( * 2); for (byte b : hash) { if ((b & 0xFF) < 0x10) { ("0"); } ((b & 0xFF)); } return (); } }
Local cache
public class LocalCacheUtil { private String CACHE_URl; private MemoryCacheUtil memoryCacheUtil; public LocalCacheUtil(MemoryCacheUtil memoryCacheUtil){ // Initialize the path to local storage CACHE_URl = ().getAbsoluteFile()+ "/test"; = memoryCacheUtil; } // Get pictures from local sdcard public Bitmap getBitmap(String url){ // Obtain the local file according to the url, encrypt the url with md5 as the file name try { String fileName = (url); File file = new File(CACHE_URl, fileName); if(()){// Determine whether the current file exists // Convert the current file into a Bitmap object Bitmap bitmap = (()); // Need to save a copy in memory (url, bitmap); return bitmap; } } catch (Exception e) { (); } return null; } // How to store pictures locally public void saveBitmap(String url,Bitmap bitmap){ try { String fileName = (url); File file = new File(CACHE_URl, fileName); // Determine whether the parent directory needs to be created File parentFile = (); if(!()){ (); } // Save Bitmap objects to a file. The higher the quality, the slower the compression speed OutputStream stream = new FileOutputStream(file); (, 100, stream);//The first parameter can set the image format, the second image compression quality, and the third image output stream } catch (Exception e) { (); } } }
3. Network cache uses asynchronous loading of AsyncTask, and there are two reasons for using it:
Run on child threads, performing time-consuming operations on network requests to avoid blockage of main thread;
and onPostExecute facilitate updating the UI to improve user experience.
public class NetCacheUtil { private MemoryCacheUtil memoryCacheUtil; private LocalCacheUtil localCacheUtil; private ListView lv_image_list; public NetCacheUtil(MemoryCacheUtil memoryCacheUtil,LocalCacheUtil localCacheUtil){ = memoryCacheUtil; = localCacheUtil; } public void display(ImageView imageView ,String url, ListView lv_image_list){ this.lv_image_list = lv_image_list; new MyAsyncTask(imageView).execute(new Object[]{url,imageView}); } class MyAsyncTask extends AsyncTask<Object, Void, Bitmap>{ private ImageView imageView; private int position; public MyAsyncTask(ImageView imageView2) { position = (Integer) (); } // Run on the main thread and make preparations. Before doInBackground, you can place a load bar to improve user experience @Override protected void onPreExecute() { (); } // Run on child thread, performing time-consuming operations @Override protected Bitmap doInBackground(Object... params) { // Get the url and download the picture String url = (String) params[0]; // Get ImageView imageView = (ImageView) params[1]; try { // Download the picture HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); ();// Connect to the network // Get the response code int resCode = (); if(resCode==200){// Access is successful // Convert the input stream returned by the server into a Bitmap object Bitmap bitmap = (()); // Save to local and memory (url, bitmap); (url, bitmap); return bitmap; } } catch (Exception e) { (); } return null; } // Run on the main thread, update the interface, after doInBackground @Override protected void onPostExecute(Bitmap result) { // Determine whether the position is still in Listview when the thread starts ImageView view = (ImageView) lv_image_list.findViewWithTag(position); if(view!=null){ (result); } (result); } } }
4. Encapsulate the third-level cache to form ImageUtil. Because the memory cache is fetched quickly, it is fetched from the memory cache first. It cannot be fetched from the -> local cache, and cannot be fetched from the -> network cache.
public class ImageUtils { private MemoryCacheUtil memoryCacheUtil; private LocalCacheUtil localCacheUtil; private NetCacheUtil netCacheUtil; public ImageUtils(){ memoryCacheUtil = new MemoryCacheUtil(); localCacheUtil = new LocalCacheUtil(memoryCacheUtil); netCacheUtil = new NetCacheUtil(memoryCacheUtil,localCacheUtil); } public void display(ImageView imageView, String url, ListView lv_photo_list) { Bitmap bitmap = null; /** * Because the memory cache is faster * Getting from memory cache, can't get -> getting from local cache, can't get -> getting from network cache */ bitmap = (url);//Fetch pictures from memory cache if(bitmap!=null){ (bitmap); return; } bitmap = (url);//Fetch pictures from local cache if(bitmap!=null){ (bitmap); return; } // Enable thread access to the network, download pictures, and display them (imageView, url,lv_photo_list); } }
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.