【发布时间】:2014-08-19 16:42:39
【问题描述】:
我试图在我的 android 应用程序中防止 OutOfMemoryError。看了很多帖子,还是解决不了。
该应用程序有后台活动,所以我认为这是主要问题。 OutOfMemoryError 仅在某些设备中发生(可能是由于 VM 堆),我需要确保此错误不会在任何设备中导致崩溃。
我最近阅读了关于 MAT(Memory Analytics 插件)的信息,并且在应用运行时执行了它,您可以在这里看到结果:
支配树
报告
在这个活动中,我为每个方向(家庭、家庭土地)设置了一个背景。两种尺寸相同(190kb,jpg)。当我创建 HPROF 文件时,活动是横向的,我之前没有运行纵向。为了达到我的目的,我可以从这个结果中得出什么结论?
如有必要,我可以添加更多信息
编辑
我也尝试使用this page的方法来避免OutOfMemoryError,但我无法得到它。这是我的代码:
decodeFromResource 类
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
public class decodeFromResource {
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and
// keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
public static Bitmap decodeSampledBitmapFromResource(Resources res, 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(res, resId, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
public static Drawable getDecodedDrawableFromResource(Resources res, int resId,
int reqWidth, int reqHeight){
return new BitmapDrawable(res, decodeSampledBitmapFromResource(res, resId, reqWidth, reqHeight));
}
}
来自主活动的 onCreate 方法
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
resources = getResources();
DisplayMetrics metrics = resources.getDisplayMetrics();
layoutHome = (LinearLayout) findViewById(R.id.home_layout);
if (resources.getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
layoutHome.setBackgroundDrawable(decodeFromResource
.getDecodedDrawableFromResource(resources, R.drawable.home,
metrics.widthPixels, metrics.heightPixels));
} else {
layoutHome.setBackgroundDrawable(decodeFromResource
.getDecodedDrawableFromResource(resources,
R.drawable.home_land, metrics.heightPixels,
metrics.widthPixels));
}
我只为背景实现了“有效加载大位图”方法,因为除此之外我只有五个非常小的小按钮。我是否还需要为他们实施该方法?你能看到任何错误吗?
【问题讨论】:
-
您在启动时或在纵向和横向之间反复切换时会出现 OOM 吗?
-
@Hans Kratz 这取决于设备。有时在启动 Home Intent 后我会得到 OOM,但有时它只在我切换方向时发生。
标签: android out-of-memory heap-memory