我的代码:
public void onClick(View v)
{
if(getCamera() != null && CameraPreview.SAFE_TO_TAKE_PICTURE)
{
getCamera().startPreview();
getCamera().takePicture(null, null, mJpegImageCallback);
}
}
private PictureCallback mJpegImageCallback = new PictureCallback()
{
public void onPictureTaken(byte[] data, Camera camera)
{
CameraPreview.SAFE_TO_TAKE_PICTURE = false;
onCameraPictureTaken(data);
BBLogUtils.logFlow("Camera: Image Taken");
}
};
CameraPreview:
public void surfaceCreated(SurfaceHolder holder)
{
// The Surface has been created, acquire the camera and tell it where
// to draw.
mCamera = Camera.open(0);
mParameters = mCamera.getParameters();
setCameraDisplayOrientation();
mCamera.setPreviewDisplay(holder);
if ( isAutoFocusSupported() )
setFocus();
if ( isFlashSupported() )
setFlash(mFlashState);
}
public void surfaceDestroyed(SurfaceHolder holder)
{
if ( mCamera != null )
{
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height)
{
// Now that the size is known, set up the camera parameters and begin
// the preview.
mPreviewWidth = width;
mPreviewHeight = height;
Camera.Size previewSize = getBestPreviewSize(width, height);
Camera.Size pictureSize = getOptimalImageSize();
holder.setFormat(format);
mParameters.setPreviewSize(previewSize.width, previewSize.height);
mParameters.setPictureSize(pictureSize.width, pictureSize.height);
mParameters.setJpegQuality(100);
mCamera.setPreviewDisplay(holder);
SAFE_TO_TAKE_PICTURE = true;
setCameraParameters();
handleFocus();
}
private void setCameraParameters()
{
mCamera.stopPreview();
mCamera.setParameters(mParameters);
mCamera.startPreview();
}
我在某处读过你需要设置safe_to_take_picture需要在拍照之前进行检查,这样才能确保在调用takepicture之前已经开始预览。我甚至明确地这样做了。即使这样,我也会遇到以下异常:
java.lang.RuntimeException: takePicture failed
E/ACRA ( 1180): at android.hardware.Camera.native_takePicture(Native Method)
E/ACRA ( 1180): at android.hardware.Camera.takePicture(Camera.java:1100)
E/ACRA ( 1180): at android.hardware.Camera.takePicture(Camera.java:1045)
E/ACRA ( 1180): at CameraClickListener.onClick(CameraClickListener.java:38)
E/ACRA ( 1180): at CameraActivity$7.onClick(CameraActivity.java:200)
E/ACRA ( 1180): at android.view.View.performClick(View.java:4240)
E/ACRA ( 1180): at android.view.View$PerformClick.run(View.java:17721)
E/ACRA ( 1180): at android.os.Handler.handleCallback(Handler.java:730)
E/ACRA ( 1180): at android.os.Handler.dispatchMessage(Handler.java:92)
E/ACRA ( 1180): at android.os.Looper.loop(Looper.java:137)