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

How to handle OOM exception for bitmap in android

我正在使用摄影应用程序从 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;
    }

改为

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

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

应该可行