【发布时间】:2014-06-03 13:18:23
【问题描述】:
我正在重写一个 Android 应用程序,其中每个活动(有几个)显示一个背景图像。用户可能会更改此图像,因此我做了以下操作:
- 已创建 MyAppApplication(扩展 Application),在每个活动的 onCreate() 中设置了对其的引用。
- MyAppApplication 有一个公共 BitmapDrawable,它在启动时应用于背景。
- 每个 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
}
然后,在活动中,我将背景设置为 backgroundImage。
应用程序第一次启动时可以这样做,但如果共享首选项发生更改,则应用程序会尝试再次解码资源,并且应用程序会在上面标记的点崩溃。请问我可以做些什么来避免这种情况?
【问题讨论】:
-
是否因 OOM 崩溃?
-
你能在这里添加你的崩溃报告(日志)吗。所以我可以帮助你。
-
它确实因 OOM 错误而崩溃,相关行是我在上面标记的行。我已经把日志here.
标签: android bitmap out-of-memory bitmapfactory