gpt4 book ai didi

java - 如何在android上缓存数据?

转载 作者:搜寻专家 更新时间:2023-11-01 08:39:38 25 4
gpt4 key购买 nike

好吧,我正在构建一个应用程序,我必须在其中显示图像和文本作为其标题。我已经成功构建了该应用程序,我可以在其中从服务器获取数据并显示它。我的问题是如何缓存数据(包含图像)并显示数据。例如,在 Instagram 中,我们得到一个由我们关注的所有人生成的提要,我们可以看到带有文本的图像,以及当我们退出应用程序并再次打开应用程序时,我们可以很容易地看到所有带有文字的图像,因为它与互联网无关。我想实现类似的东西。请帮助我。谢谢你

最佳答案

您可以使用 LRUCache (Least Recently Used,首先丢弃最近最少使用的项目)来存储图像。来自 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com