Pregunta

I wanted to know what is the best practice for writing the SurfaceView surfaceDestroyed method and surfaceCreated method, and also the onPause and onResume methods of the Activity using the camera? There are several posts but none of them seem to help.

Here is the code:

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();
}

Activity onResume

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

Activity 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;
    }
}

In initializeCamera, I do the following:

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

}

With this setup, I get the error Method Called Before Release() when I run the app. Where am I going wrong?

¿Fue útil?

Solución

It should be like this:

@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);
        }
    }

Nothing is needed in surfaceDestroyed

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top