如何在android中处理位图的OOM异常

时间:2016-04-09 07:10:18

标签: android android-canvas textview android-bitmap

我正在使用照片应用程序,我在TextView创建位图。当我尝试从大文本应用程序创建位图成为崩溃。和LogCat显示内存不足例外

创建位图的方法

protected Bitmap getBitmapFromView(View v) {
        int w, h;
        Bitmap b = null;
        KeyboardActivity.setTextInTextView((TextView) v, this,
                this.tvClass.text);
        ((TextView) v).setMinLines(1);
        if (this.tvClass.isStrick) {
            ((TextView) v).setPaintFlags(((TextView) v).getPaintFlags() | 16);
        } else {
            ((TextView) v).setPaintFlags(((TextView) v).getPaintFlags() & -17);
        }
        if (this.tvClass.isUnderline) {
            ((TextView) v).setPaintFlags(((TextView) v).getPaintFlags() | 8);
        } else {
            ((TextView) v).setPaintFlags(((TextView) v).getPaintFlags() & -9);
        }
        if (this.tvClass.isBold) {
            ((TextView) v).setPaintFlags(((TextView) v).getPaintFlags() | 32);
        } else {
            ((TextView) v).setPaintFlags(((TextView) v).getPaintFlags() & -33);
        }
        ((TextView) v)
                .setGravity(this.tvClass.gravity1 | this.tvClass.gravity2);
        try {
            if (VERSION.SDK_INT <= 25) {
                v.measure(0, 0);
                w = v.getMeasuredWidth() + 10;
                h = v.getMeasuredHeight();
                v.layout(0, 0, w, h);
            } else {
                w = v.getWidth();
                h = v.getHeight();
            }
            if (w == 0) {
                w = 110;
            }
            if (h == 0) {
                h = 70;
            }
        } catch (Exception e) {
            w = 110;
            h = 7;
        }

        try {
            // this line generate OOM Exception 
            b = Bitmap.createBitmap(w, h, Config.ARGB_8888);
        } catch (Exception e) {
           // Exception is not handle
        }

        Canvas c = new Canvas(b);
        v.draw(c);
        c.drawColor((((255 - this.tvClass.alpha) * 2) & 1) << 24, Mode.DST_OUT);
        c.save();
        c.rotate(90.0f, 0.0f, 0.0f);
        v.setVisibility(8);
        c.restore();
        return b;
    }

1 个答案:

答案 0 :(得分:1)

更改为

 catch(OutOfMemoryError oom){
        // out of memory does not extends from Exception
  }

http://developer.android.com/reference/java/lang/OutOfMemoryError.html

那应该有用