OnResume Camera Reinit Black Screen

2019-04-25 19:04发布

问题:

I have a problem. After initializing the camera for a preview and bringing another app into focus, then back to my app: the preview shows up black. If I continue to take a picture, it takes a picture of where I point the camera normally.

Am I doing something wrong on the OnResume() override? Relative code is below:

public void ReleaseCamera()
    {
        if (myCamera != null)
        {
            myCamera.Release();
            myCamera = null;
        }
    }

protected override void OnPause()
    {
        base.OnPause();

        if (myButtonState == ButtonState.CameraActive)
            ReleaseCamera();
    }

protected override void OnResume()
    {
        base.OnResume();

        if (myButtonState == ButtonState.CameraActive)
            InitializeCamera();
    }

private void InitializeCamera()
    {
        SurfaceView mySurfaceView = FindViewById<SurfaceView>(Resource.Id.surfaceView1);

        myCamera = Android.Hardware.Camera.Open(cameraNumber);
        Android.Hardware.Camera.Parameters p = myCamera.GetParameters();

        myCamera.SetDisplayOrientation(90); // Portrait
        myCamera.SetPreviewDisplay(mySurfaceView.Holder);
        myCamera.StartPreview();
    }

Thank you for your help. :)

回答1:

onResume() gets called too early. You don't have the surface holder ready at this stage. You can try to introduce onPostResume() handler in your Activity, and/or handle the SurfaceHolder.Callback.surfaceChanged() event.