gpt4 book ai didi

如果多次使用,Android BitmapFactory.decodeResource 内存不足

转载 作者:行者123 更新时间:2023-11-30 02:51:49 25 4
gpt4 key购买 nike

我正在重新编写一个 Android 应用程序,其中每个 Activity (有多个)都显示背景图片。用户可能会更改此图像,因此我已完成以下操作:

  1. 创建了 MyAppApplication(扩展了 Application),在每个 Activity 的 onCreate() 中设置了对它的引用。
  2. MyAppApplication 有一个在启动时应用于背景的公共(public) BitmapDrawable。
  3. 每个 Activity 都会监听 SharedPreferences 的变化,并在发生此类变化时重新加载背景图片。

这是我用来设置图像的部分代码,基于 http://developer.android.com/training/displaying-bitmaps/load-bitmap.html :

Bitmap bitmap = decodeBitmap(R.drawable.background_image, screen_width, screen_height);
}
public BitmapDrawable backgroundImage = new BitmapDrawable(bitmap);

public Bitmap decodeBitmap(int resId, int reqWidth, int reqHeight)
{
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(getResources(), resId, options);

// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(getResources(), resId, options); // crashes here
}

然后,在 Activity 中,我将背景设置为 backgroundImage。

应用程序第一次启动时可以正常工作,但如果共享首选项发生更改,则应用程序会尝试再次解码资源,应用程序会在上面标记的位置崩溃。请问我可以做些什么来避免这种情况?

最佳答案

每次使用完 Bitmap 后,都应该释放它们,因为它们会占用大量内存。

在 onDestroy() 中你应该这样写:

bitmap.recycle();
bitmap = null;

每当您停止使用位图时,您也应该调用这些行。

关于如果多次使用,Android BitmapFactory.decodeResource 内存不足,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24016265/

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