嗯,我正在构建一个应用程序,我必须在其中显示图像和文本作为其标题。我已经成功完成了应用程序的构建,我可以在其中从服务器获取数据并显示它。我的问题是我如何缓存数据(包含图像)并显示数据。例如,在 Instagram 中,我们得到我们关注的所有人生成的提要,我们可以看到带有文本的图像,当我们退出应用程序并再次打开应用程序时,我们可以轻松地看到所有带有文本的图像,因为它与互联网无关。我想实现类似的东西。请帮助我。 谢谢您
最佳答案
您可以使用LRUCache (最近最少使用的,首先丢弃最近最少使用的项目)来存储图像。来自 Android 文档:
A cache that holds strong references to a limited number of values. Each time a value is accessed, it is moved to the head of a queue. When a value is added to a full cache, the value at the end of that queue is evicted and may become eligible for garbage collection.
这是一个内存缓存,因此我们可以缓存的图像数量是有限的。确定缓存大小的一个好方法是根据可用堆内存来计算它。以下代码是一个示例
int memClass = ((ActivityManager)activity.getSystemService( Context.ACTIVITY_SERVICE)).getMemoryClass();
int cacheSize = 1024 * 1024 * memClass / 8;
LruCache cache = new LruCache<String, Bitmap>(cacheSize);
我们使用Bitmap
方法来确定放入缓存中的每个元素的大小。在此示例中,我们使用 1/8 的可用堆内存。如果需要,应增加缓存大小。
public class AppCache extends LruCache<String, Bitmap>
{
public AppCache(int maxSize)
{
super(maxSize);
}
@Override
protected int sizeOf(String key, Bitmap value)
{
return value.getByteCount();
}
@Override
protected void entryRemoved(boolean evicted, String key, Bitmap oldValue, Bitmap newValue)
{
oldValue.recycle();
}
}
除此之外,请查看有关“缓存位图”的 Android 文档,其中说道:
A memory cache offers fast access to bitmaps at the cost of taking up valuable application memory. The LruCache class (also available in the Support Library for use back to API Level 4) is particularly well suited to the task of caching bitmaps, keeping recently referenced objects in a strong referenced LinkedHashMap and evicting the least recently used member before the cache exceeds its designated size.
http://developer.android.com/training/displaying-bitmaps/cache-bitmap.html
关于java - 如何在Android上缓存数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33964123/