Android Camera和SurfaceView:正确的发布方式

时间:2014-04-15 09:40:52

标签: android-camera

我想知道使用相机编写SurfaceView surfaceDestroyed方法和surfaceCreated方法以及Activity的onPause和onResume方法的最佳做法是什么?有几个帖子,但似乎都没有帮助。

以下是代码:

SurfaceCreated

public void surfaceCreated(SurfaceHolder holder) {
    try {
        Log.d(TAG,"Surface Created");
        mCamera.setPreviewDisplay(holder);
        mCamera.startPreview();
    } catch (IOException e) {
        Log.d(TAG, "Error setting camera preview: " + e.getMessage());
    }
}

SurfaceDestroyed

public void surfaceDestroyed(SurfaceHolder holder) {
    this.getHolder().removeCallback(this);
    mCamera.stopPreview();
    mCamera.release();
}

活动onResume

protected void onResume() {
    super.onResume();
    mCamera.setPreviewCallback(null);
    Log.d(TAG,"onResume Called");
    if (mCamera==null){
    mCamera=getCameraInstance();
    }
    initializeCamera(mCamera);      
}

活动onPause

protected void onPause() {
    super.onPause();
    Log.d(TAG,"onPause Called");
    if(mCamera!=null){
        mCamera.stopPreview();
        mCamera.setPreviewCallback(null);
        mPreview.getHolder().removeCallback(mPreview);
        preview.removeView(mPreview);
        mCamera.release();
        mCamera = null;
    }
}

在initializeCamera中,我执行以下操作:

private void initializeCamera(Camera mCamera) {
    mPreview = new InternalCameraPreview(this, mCamera);
    preview = (FrameLayout) findViewById(R.id.camera_preview);
    preview.addView(mPreview);

}

通过此设置,我在运行应用程序时收到错误Method Called Before Release()。我哪里错了?

2 个答案:

答案 0 :(得分:3)

应该是这样的:

@Override
    public void onPause() {
        super.onPause();

        if (mCamera != null){
            //              mCamera.setPreviewCallback(null);
            mPreview.getHolder().removeCallback(mPreview);
            releaseMediaRecorder();
            mCamera.release();        // release the camera for other applications
            mCamera = null;

        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mCamera == null) {
            mCamera=getCameraInstance();
            mPreview = new CameraPreview(this.getActivity(), mCamera);
            preview.addView(mPreview);
        }
    }

surfaceDestroyed

中无需任何操作

答案 1 :(得分:1)

根据Android文档,相机>部分控制相机

  

使用相机完成申请后,是时候清理了。   特别是,您必须释放Camera对象,否则您将面临风险   崩溃其他应用程序,包括您自己的新实例   应用

     

什么时候应该停止预览并释放相机?好吧,有   你的预览表面被破坏是一个很好的提示,是时候了   停止预览并释放相机

private void stopPreviewAndFreeCamera() {

    if (mCamera != null) {
        // Call stopPreview() to stop updating the preview surface.
        mCamera.stopPreview();

        // Important: Call release() to release the camera for use by other
        // applications. Applications should release the camera immediately
        // during onPause() and re-open() it during onResume()).
        mCamera.release();

        mCamera = null;
    }
}