SurfaceView to preview the camera will not be destroyed when you press the power button

I want to implement a camera preview. To do this, I have a custom view CameraView extends ViewGroup, which in the constructor programmatically creates a surfaceView.

I have the following components (extremely simplified for beverity):

ScannerFragment.java

public View onCreateView(..) {
   //inflate view and get cameraView
}

public void onResume() {
   //open camera -> set rotation -> startPreview (in a thread) -> 
   //set preview callback -> start decoding worker
}

public void onPause() {
   // stop decoding worker -> stop Preview -> release camera
}

CameraView.java extends ViewGroup

public void setUpCalledInConstructor(Context context) {
   //create a surfaceview and add it to this viewgroup ->
   //get SurfaceHolder and set callback
}

/* SurfaceHolder.Callback */
public void surfaceCreated(SurfaceHolder holder) {
   camera.setPreviewDisplay(holder);
}

public void surfaceDestroyed(SurfaceHolder holder) {
    //NOTHING is done here
}

public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
    camera.getParameters().setPreviewSize(previewSize.width, previewSize.height);
}

fragment_scanner.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.myapp.camera.CameraView
        android:id="@+id/cameraPreview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</RelativeLayout>

I think I set the life cycle correctly (getting the resources of onResume (), releasing it onPause () roughly), and the following works just fine:

  • clicking on the house and returning
  • pressing the Taskswitcher button and returning
  • rotation
  • cancellation (of course)

, , . : , . , , .

, , , , surfaceView , .. SurfaceHolder.Callback.surfaceDestroyed(SurfaceHolder holder) . , ( ) - , , , "surfaceDestroyed" .

, . surfaceDestroyed(), . , View, , . /, , , . .

+4
2

 public void onDestroy() {
 // stop decoding worker -> stop Preview -> release camera
}

onPause(), .

Camera(),

    private void releaseCamera() {
    if (myCamera != null) {
        FrameLayout preview = (FrameLayout) findViewById(R.id.cameraPreview);
        preview.removeView(myPreview);
        myCamera.setPreviewCallback(null);
        myCamera.release();
        myCamera = null;

    }
}

CameraPreview (myPreview), . .

+1

mPreview.getHolder() removeCallback (mPreview). ?

0

All Articles