All the answers in this thread mention an arbitrary delay where as the root cause of this problem is not addressed.
The camera in an android phone does the autofocus activity after the start of the preview and before capturing the picture. The code snippet in the question mentions call to mCamera.takePicture(null, mPictureCallback,mPictureCallback);
right after mCamera.startPreview();
.
Taking the picture during the autofocus process gives rise to the exposure issues in the image captured, resulting into dark photos. The delays mentioned in the answers give android the time to complete its autofocus and the image captured is perfect. This might not be the case with every device and an arbitrary number may result into failure on some devices.
My recommendation would be following code snippet -
Camera.AutoFocusCallback autoFocusCallBack = new Camera.AutoFocusCallback();
static autoFocusCallBack(){
mCamera.takePicture(null, mPictureCallback,
mPictureCallback);
}
if (mCamera != null) {
try {
mCamera.setPreviewDisplay(mSurfaceHolder);
mCamera.startPreview();
mCamera.autoFocus(autoFocusCallBack);
} catch (IOException e) {
e.printStackTrace();
}
}
This flow ensures that the takePicture()
is called in the autofocus callback implying autofocus was successful. This will give a proper image with appropriate exposure and brightness.
This will also remove the arbitrary delay.
Read this link for Camera.AutoFocus()
.
Read this link for Camera.takePicture()
.
Read this link for Camera.startPreview()
.