解决java.lang.RuntimeException: Camera is being used after Camera.release() was called

java.lang.RuntimeException: Camera is being used after Camera.release() was called

在相机开发中,打开相机后点返回,偶尔会出现如上所示的异常,解决代码如下:

@BindView(R.id.sv_preview)
SurfaceView mSvPreview;

private BaseCameraManager cameraManager;

@Override
protected void onResume() {
    super.onResume();

    int hasCameraPermission = ContextCompat.checkSelfPermission(mActivity, Manifest.permission.CAMERA);
    if (hasCameraPermission != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(mActivity, new String[]{Manifest.permission.CAMERA},
                MY_PERMISSIONS_REQUEST_CAMERA);
    }

    //region 这里调用初始化照相机并设置SurfaceHolder的回调以解决按下home键或者按下最近应用菜单键再返回扫码界面时相机不显示的问题

    cameraManager = new CameraManager(getApplication());

    setSurfaceViewVisible(true);

    cameraManager.setOnResultListener(this);

    mSvPreview.getHolder().addCallback(this);
    //endregion
}

@Override
public void surfaceDestroyed(SurfaceHolder holder) {        

    setEmptyViewVisible(true);    
    //解决java.lang.RuntimeException: Camera is being used after Camera.release() was called异常    
    holder.removeCallback(this);    

    cameraManager.releaseCamera();
}

BaseCameraManager源码如下:

/**
 * CameraManager的基类
 * Created by Jack on 2016/7/1 12:55
 * Email: zhuochangjing@foxmail.com
 */
public abstract class BaseCameraManager {
    private Point qrBoxSize;

    boolean hook = false;
    int rotate;
    int count = 0;
    boolean isRelease = true;
    ExecutorService executor;
    int displayOrientation;
    private MultiFormatReader reader;
    OnResultListener onResultListener;
    protected Context context;

    BaseCameraManager(Context context) {
        this.context = context;
        executor = Executors.newSingleThreadExecutor();
        reader = new MultiFormatReader();
        qrBoxSize = new Point();
        qrBoxSize.x = (int) context.getResources().getDimension(R.dimen.width_qr_box_view);
        qrBoxSize.y = (int) context.getResources().getDimension(R.dimen.height_qr_box_view);
    }

    QRResult getCodeValue(byte[] data, Point previewSize) {
        Bitmap bitmap = null;
        ByteArrayOutputStream stream = new ByteArrayOutputStream(data.length);
        YuvImage image = new YuvImage(data, ImageFormat.NV21, previewSize.x, previewSize.y, null);
        int left = previewSize.x - qrBoxSize.x >> 1;
        int right = previewSize.x + qrBoxSize.x >> 1;
        int top = previewSize.y - qrBoxSize.y >> 1;
        int bottom = previewSize.y + qrBoxSize.y >> 1;
        Rect rect = new Rect(left, top, right, bottom);
        if (image.compressToJpeg(rect, 100, stream)) {
            byte[] bytes = stream.toByteArray();
            bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
        }
        try {
            stream.close();
        } catch (IOException e) {
            Log.e("onPreviewFrame", e.toString());
        }

        if (displayOrientation > 0) {
            Matrix matrix = new Matrix();
            matrix.postRotate(displayOrientation);
            assert bitmap != null;
            Bitmap newBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, false);
            bitmap.recycle();
            bitmap = newBitmap;
        }

        assert bitmap != null;
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        int[] pixels = new int[width * height];
        bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
        Result result = QRUtils.decode(new RGBLuminanceSource(width, height, pixels), reader);
        if (result != null) {
            return new QRResult(bitmap, result);
        } else {
            bitmap.recycle();
            return null;
        }
    }

    public void setHook(boolean hook) {
        this.hook = hook;
    }

    public void setOnResultListener(OnResultListener onResultListener) {
        this.onResultListener = onResultListener;
    }

    public void shutdownExecutor() {
        executor.shutdown();
    }

    public ExecutorService getExecutor() {
        return executor;
    }

    public void setRotate(int rotate) {
        this.rotate = rotate;
    }

    public abstract void connectCamera(SurfaceHolder surfaceHolder);

    public abstract void setCameraParameter();

    public abstract void startCapture();

    public abstract void releaseCamera();

    public interface OnResultListener {
        void onResult(QRResult qrResult);
    }
}

CameraManager源码如下:

/**
 * This class is for android targets below android 5.0 and it uses old camera api
 * Created by Jack on 2016/7/1 12:55
 * Email: zhuochangjing@foxmail.com
 */
@SuppressWarnings("deprecation")
public class CameraManager extends BaseCameraManager implements Camera.AutoFocusCallback, Camera.PreviewCallback {

    private Camera camera;

    public CameraManager(Context context) {
        super(context);
    }

    @Override
    public void onAutoFocus(boolean success, Camera camera) {
        if (hook || isRelease) return;
        camera.setOneShotPreviewCallback(this);
    }

    @Override
    public void connectCamera(SurfaceHolder surfaceHolder) {
        if (!isRelease) return;
        try {
            camera = Camera.open();
            isRelease = false;
            camera.setPreviewDisplay(surfaceHolder);
            setCameraParameter();
            camera.startPreview();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void releaseCamera() {
        if (isRelease) return;
        isRelease = true;
        camera.setPreviewCallback(null);
        camera.cancelAutoFocus();
        camera.stopPreview();
        try {
            camera.setPreviewDisplay(null);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        camera.release();
        camera = null;
    }

    @Override
    public void startCapture() {
        if (hook || isRelease || executor.isShutdown()) return;
        executor.execute(new Runnable() {
            @Override
            public void run() {
                camera.autoFocus(CameraManager.this);
            }
        });
    }

    @Override
    public void setCameraParameter() {
        Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
        Camera.getCameraInfo(0, cameraInfo);
        int degrees = 0;
        switch (rotate) {
            case Surface.ROTATION_0: {
                degrees = 0;
                break;
            }
            case Surface.ROTATION_90: {
                degrees = 90;
                break;
            }
            case Surface.ROTATION_180: {
                degrees = 180;
                break;
            }
            case Surface.ROTATION_270: {
                degrees = 270;
                break;
            }
        }

        if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
            displayOrientation = (cameraInfo.orientation + degrees) % 360;
            displayOrientation = (360 - displayOrientation) % 360;
        } else {
            displayOrientation = (cameraInfo.orientation - degrees + 360) % 360;
        }

        /** Warning : may throw exception with parameters not supported */
        Camera.Parameters parameters = camera.getParameters();
        List<Camera.Size> previewSizes = parameters.getSupportedPreviewSizes();
        Camera.Size bestSize = previewSizes.get(0);
        for (int i = 1; i < previewSizes.size(); i++) {
            if (previewSizes.get(i).width * previewSizes.get(i).height > bestSize.width * bestSize.height) {
                bestSize = previewSizes.get(i);
            }
        }
        parameters.setPreviewSize(bestSize.width, bestSize.height);

        List<Camera.Size> pictureSizes = parameters.getSupportedPictureSizes();
        bestSize = pictureSizes.get(0);
        for (int i = 1; i < pictureSizes.size(); i++) {
            if (pictureSizes.get(i).width * pictureSizes.get(i).height > bestSize.width * bestSize.height) {
                bestSize = pictureSizes.get(i);
            }
        }
        parameters.setPictureSize(bestSize.width, bestSize.height);
        camera.setParameters(parameters);
        camera.setDisplayOrientation(displayOrientation);
    }

    @Override
    public void onPreviewFrame(final byte[] data, final Camera camera) {
        if (hook || executor.isShutdown()) return;
        Observable
                .just(camera.getParameters().getPreviewSize())
                .subscribeOn(Schedulers.from(executor))
                .map(new Func1<Camera.Size, QRResult>() {
                    @Override
                    public QRResult call(Camera.Size size) {
                        return getCodeValue(data, new Point(size.width, size.height));
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<QRResult>() {
                    @Override
                    public void call(QRResult qrResult) {
                        if (qrResult == null) {
                            count++;
                            startCapture();
                            return;
                        }
                        QRUtils.vibrate(context);
                        if (onResultListener != null) {
                            onResultListener.onResult(qrResult);
                        }
                        count = 0;
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        Log.e("CameraManager", "getCodeValue() failed .");
                    }
                });
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 211,423评论 6 491
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,147评论 2 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,019评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,443评论 1 283
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,535评论 6 385
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,798评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,941评论 3 407
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,704评论 0 266
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,152评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,494评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,629评论 1 340
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,295评论 4 329
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,901评论 3 313
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,742评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,978评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,333评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,499评论 2 348

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 171,761评论 25 707
  • 西江月 闻醉故人渐远,此中孤单谁寒? 酒倾杯空两三言,挑惹清灯愁点。 冬夜寂风谁动?凭栏倚月惜残。 暗香晚籁忆流年...
    寒菊阅读 198评论 4 4
  • 目前App的地图功能越来越普遍了,导航也是斯通见惯了,基于这一块的可通用性,我简单封装了一下导航的功能。效果如下(...
    silence_xz阅读 690评论 0 0
  • 数据作为数据分析的目标与对象无时无刻不充斥在我们的生活中,用数据说话或是数据为王的准则被人们时时刻刻地挂在嘴边,那...
    IT书友会阅读 718评论 0 0