Three level caching mechanism of pictures in Android

We can't let users download pictures from the network every time we load them, which not only wastes traffic, but also affects the user experience. Therefore, the operation mechanism of picture caching is introduced into Android.

Principle:

First, download the picture on the network according to the network address of the picture, and cache the picture into the memory cache and strong reference, that is, lrucache. If there is insufficient space in the strong reference, the image object stored earlier will be expelled to the soft reference for storage, and then the image will be cached in the file (internal storage and external storage); When reading a picture, first read the memory cache to judge whether there is a picture in the strong reference. If there is a picture in the strong reference, read it directly. If there is no picture in the strong reference, judge whether there is a picture in the soft reference. If there is a picture in the soft reference, add the picture in the soft reference to the strong reference and delete the data in the soft reference. If there is no picture in the soft reference, The file store is read. If the file store does not exist, the network is loaded.

Download: Network -- memory -- File

Read: memory -- strong reference -- soft reference -- File -- Network

This is such a process. Let's use a simple demo to demonstrate your image level 3 cache. There is only one interface in this demo. On the interface, an ImageView is used to display the image and a button is used to load the image when clicking. The layout is as follows: @ h_ 403_ 15@

To download data from the network, you need to store it in the local SD card, so don't forget to add network access permission, network status access permission and write content to external storage devices:

Next, create an httputils tool class to access the network. The code is as follows:

There are also tool classes for operating external storage:

In this example, the pictures are stored in the SD card root directory by default.

Then comes the main main function:

The basic ideas are written in detail in the code comments. The main idea is to customize a class to inherit the lrucache of the system, implement the two main methods sizeof () and entryremoved (), and rewrite its constructor.

The above is all about the three-level caching mechanism of pictures in Android introduced by Xiaobian. I hope it will help you. If you have any questions, please leave me a message, and Xiaobian will reply to you in time. Thank you very much for your support for the programming tips website!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>