Android应用程序OutOfMemory异常问题

时间:2016-10-23 07:02:48

标签: java android out-of-memory

因为我正在学习android应用程序开发。我最近遇到了一些与我的应用程序OutOfMemory异常的问题。 image1显示日志详细信息,image2显示错误行。

确切的错误描述是:java.lang.OutOfMemoryError: Failed to allocate a 48231264 byte allocation with 4194304 free bytes and 14MB until OOM。如果我能解决问题,那将是一种解脱。

谢谢。

1 个答案:

答案 0 :(得分:-1)

图像太大了。这可以帮助您:https://developer.android.com/training/displaying-bitmaps/load-bitmap.html#read-bitmap您还可以使用外部资源库,例如Universal Image Loader或Picasso。

    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 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;
}