按下Android平板电脑上的电源按钮时,表面视图相机会冻结并且不会释放

时间:2015-05-29 08:06:10

标签: android android-camera

当我的应用程序打开并按下电源Button并重新打开平板电脑时,Camera挂起。我曾尝试再次在onResume()方法上设置SurfaceView相机,但无法解决问题,并尝试启动(camera1.startpreview()),但我仍面临同样的问题。

我的Surface View的相机代码是:

SurfaceView cameraPreview1;
SurfaceHolder previewHolder1;
public static  Camera camera2;
boolean inPreview;

@Override
protected void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  inPreview = false;

  cameraPreview1 = (SurfaceView)findViewById(R.id.cameraPreview1);
  previewHolder1 = cameraPreview1.getHolder();
  previewHolder1.addCallback(surfaceCallback);
  previewHolder1.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

 }
@Override
    public void onResume() {
      super.onResume();


      camera2=Camera.open(1);
      mPicture1 = getPictureCallback();


    }

    @Override
    public void onPause() {


      super.onPause();
        //when on Pause, release camera in order to be used from other applications

        releaseCamera();
    }

    private void releaseCamera() {
        // stop and release camera
        if (camera2 != null) {
            camera2.release();
            camera2 = null;
        }
    }

     SurfaceHolder.Callback surfaceCallback=new SurfaceHolder.Callback() {
        public void surfaceCreated(SurfaceHolder holder) {
            try {
                camera2.setPreviewDisplay(previewHolder1);  
            }
            catch (Throwable t) {
                Log.e(TAG, "Exception in setPreviewDisplay()", t);
            }
        }

        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
            Camera.Parameters parameters=camera2.getParameters();
            Camera.Size size=getBestPreviewSize(width, height, parameters);

            if (size!=null) {
                parameters.setPreviewSize(size.width, size.height);
                camera2.setParameters(parameters);
                camera2.startPreview();
                inPreview=true;
            }
    }

        public void surfaceDestroyed(SurfaceHolder holder) {
            // not used

        }

1 个答案:

答案 0 :(得分:1)

您正在setPreviewDisplay()中呼叫surfaceCreated(),但当您关闭屏幕并使用电源按钮(see notes here)重新打开时,表面不一定会被销毁并重新创建。我不认为相机是挂起的,我认为它不会将预览帧发送到Surface,因为surfaceCreated()没有被第二次调用。

解决此问题的方法是通过在surfaceCreated()中设置静态变量并在surfaceDestroyed()中清除它来检测Surface是否已创建。如果您在输入onResume()时已经设置了Surface,则需要在新的Camera对象上调用setPreviewDisplay()

Grafika的“texture from camera”活动演示了使用静态变量跟踪Surface。 FWIW,Grafika的“连续捕捉”活动gets this wrong