由于图像缓存导致的Android OOM错误



如果你认为我正在开发的应用程序像facebook一样(至少这会给你一个我正在做的事情的背景),你会更容易理解这一点。我有一个活动使用navigationdrawer在片段之间交换,每个片段都可能有一到几个"子片段"——把这些想象成单独的帖子,其中包含文本视图、几个按钮和ImageView。当创建"容器片段"时,我会调用服务器并获取制作所有"子片段"所需的数据。然后,我对数据进行迭代,并将所有"子片段"添加到"容器片段"的视图中。

我注意到我似乎使用了过高的内存量(大约129MB)。

当创建子片段时,我调用这个异步任务,它从服务器中提取每个片段所需的图像,并将它们放置在它们的ImageView中。

public class URLImageFactory extends AsyncTask<String, Void, Bitmap>
{
ImageView imgView;
private static final ImgCache mCache = new ImgCache();
public URLImageFactory(ImageView bmImage) {
this.imgView = bmImage;
}
@Override
protected Bitmap doInBackground(String... urls) {
String urldisplay = Config.SERVER_URL + urls[0].replaceAll("\s+","%20");
Bitmap bitmap = null;
//If it is in the cache don't bother pulling it from the server
if(bitmap != null)
{
return bitmap;
}
try {
InputStream in = new java.net.URL(urldisplay).openStream();
//This is in case we are using match_parent/wrap content
if(imgView.getWidth() == 0 || imgView.getHeight() == 0)
{
bitmap = BitmapFactory.decodeStream(in);
} else {
bitmap = Bitmap.createScaledBitmap(BitmapFactory.decodeStream(in),
imgView.getWidth(), imgView.getHeight(), false);
}
mCache.put(urldisplay,bitmap);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap result) {
imgView.setImageBitmap(result);
}
}

我已经做了一个基本的尝试来缓存图像以加快的进程

公共类ImgCache扩展LruCache{

public ImgCache() {
super( calculateCacheSize() );
}
public static int calculateCacheSize()
{
int maxMemory = (int) Runtime.getRuntime().maxMemory() / 8;
int cacheSize = maxMemory;
return cacheSize;
}
@Override
protected int sizeOf( String key, Bitmap value ) {
return value.getByteCount() / 1024;
}
}

我的应用程序因outOfMemory异常而崩溃。我还注意到,当我的"容器碎片"被换成另一个时。。。通常是结构相似的片段。。。这些子片段的onPause()和onStop()没有被激发。如果有帮助的话,子片段是静态内部类,而容器片段不是。我认为这是一个位图相关的问题,但我不确定。当父级点击onPause时,我曾尝试在所有子片段上使用TransactionManager.remove(fragment),但似乎没有帮助。

您将每个对象的字节数除以1024,但仅将可用内存除以8;结果是LRU高速缓存可以填充多达128倍的可用内存。将/ 1024sizeOf中移除,您应该表现良好。

最新更新