Android锁屏出现java.lang.RuntimeException: Camera is being used after Camera.release() was called

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

        在相机开发中,打开相机显示预览,然后按关机键锁屏,出现上述错误,程序崩溃。

        原来代码如下:

@Override
    public void surfaceDestroyed(SurfaceHolder arg0) {
        // TODO Auto-generated method stub
        //super.onDestroy();
        if(camera != null) {
//            holder.removeCallback(this);
//            camera.setPreviewCallback(null);
            camera.stopPreview();
        }
        holder = null;
    }

 @Override
    protected void onPause() {
        super.onPause();
        finish();//如果点home键,销毁当前页,返回前一页。
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(camera != null) {
            camera.release();
        }
        finish();
    }

       之前如果点击home键,再点APP图标进入程序,相机预览界面黑屏,要返回上一页再重新进入当前页相机预览界面才正常显示。后来我想了个偷懒的做法,在onPause方法里添加finish()方法,如果点home键,则销毁当前页,返回前一页。

       现在又出现了一个新问题,如果按关机键锁屏,就会出现上面的错误。想到应该是activity的生命周期问题,就在清单文件里配置了禁止横竖屏切换,还是出现上述错误。然后网上搜解决方法,有的说在surfaceDestroyed()添加holder.removeCallback(this),有的说添加holder.removeCallback(this)。经测试,无效。后来在onDestroy方法里camera.release()后添加camera = null,问题解决。

       修改后的代码:

@Override
    protected void onDestroy() {
        super.onDestroy();
        if(camera != null) {
            camera.release();
            camera = null;
        }
        finish();
    }

相关帖子:
java.lang.RuntimeException: Camera is being used after Camera.release() was called

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

    原文作者:java锁
    原文地址: https://blog.csdn.net/pbm863521/article/details/75111379
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞