How to effectively re-start the preview having tak

2019-08-28 23:30发布

问题:

I am attempting to code a tool that takes pictures at a dedicated interval (like a timelapse) and am having difficulty getting the camera to reset following the first capture so that it can then start on the next photo.

Here is a sample of the code used:

// gets called with the oncreate method and loads a preview fine
public void startUpPreview(){ 
    mCamera = getCameraInstance();
    mPreview = new CameraPreview(this, mCamera);
    FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
    preview.addView(mPreview);
}

// gets called from a later loop
public void getPicture() {
    mCamera.takePicture(null, null, mPicture);
    releaseCamera();
    startUpPreview();
}

With the code above, it throws the error:

java.lang.RuntimeException: Method called after release()

I am using the release code taken directly from the SDK guide which works otherwise:

private void releaseCamera(){
    if (mCamera != null){
        mCamera.release();        
        mCamera = null;
    }
}

For a single picture adding a delay with a sleeping thread makes it work:

try {
        Thread.sleep(1000);
        releaseCamera();
        startUpPreview();
} catch(InterruptedException ex) {
        Thread.currentThread().interrupt();
}

But this code does not work within a loop when attempting to take more than one picture. I assume that the loop is completing before all of that photo taking can catch up.

Thanks in advance for any help that any one can provide.

回答1:

takePicture() starts the capture process which ends with an (asynchronous) call to onPictureTaken() callback. You should not release camera before it is over.

So the pseudo-code that will perform a loop look like this:

onCLick() { // <-- start the loop
  count = 0;
  takePicture()
}

onPictureTaken() {
  savePicture(count);
  count++;
  if (count < maxCount) {
      mCamera.startPreview();
      mHandler.postDelayed(runTakePicture(), 1000);
  }
  else {
      releaseCamera();
  }
}

runTakePicture() {
   return new Runnable() {
      public void run() {
        mCamera.takePicture();
      }
   }
}