How to recover camera preview from sleep?

删除回忆录丶 提交于 2019-11-30 08:35:43

问题


I have an application that shows camera preview and I would like the user to be able to put the phone to sleep and then wake it so that my application will recover correctly. The problem is that when returning from sleep the camera preview won't restart.

I have implemented the camera preview as is presented in the api demos, but it seems that the api demo example works only through sheer luck. In the example the screen orientation is forced to landscape, which means that the phone will go through configuration change every time the phone goes to sleep, since the lockscreen is in portrait mode. If the portrait mode is used in the camera preview application (like in mine), the bug surfaces.

I have gathered that the bug is related to recreation of the surfaceview. The surface should be destroyed always when going to onPause and then recreated after onResume, but this doesn't happen when going to sleep. It seems that I have to destroy the whole activity and then recreate it to get the camera preview to work again. I would like to be able to just recreate the surfaceview.

Is there a way to force the recreation of the surfaceview other than just recreating the whole activity?


回答1:


One solution maybe setting the surfaceview to invisible and visible again in onResume(), this makes the surfaceview destroy and recreates.




回答2:


I was having the same issue and here's why:

The onPause method does not recycle the CameraPreview class I made (that implements SurfaceView Callbacks). Instead of trying to re instantiate that entire object itself, i merely updated the camera object reference i was passing it to be either

null

or

cameraPreview.setCamera(mCamera);

I called a getCameraInstance method to re initialize the camera, then passed it into the preivew object.

Now the problem is here:

private void initializeCameraView(){

    RelativeLayout preview = (RelativeLayout)rootView.findViewById(R.id.camera_preview);

    preview.addView(cameraPreview);
}

in onResume, i called this method to re initialize the cameraPreview object. However, it was freezing because I was trying to add another cameraPreview to the preview view. This was my fix, plain and simple. If it already exists, remove it, then put it right back in. Hope this helps!

private void initializeCameraView(){

    RelativeLayout preview = (RelativeLayout)rootView.findViewById(R.id.camera_preview);
    //removes the problem with the camera freezing onResume
    if(cameraPreview != null) {
        preview.removeView(cameraPreview);
    }
    preview.addView(cameraPreview);
}


来源:https://stackoverflow.com/questions/6519120/how-to-recover-camera-preview-from-sleep

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!