android camera2 api focus lock
This android tutorial describes how to obtain the android camera2 api focus lock, which is required prior to capturing a still image.
GET CODE
You can get it from here https://github.com/mobapptuts/recyclerview_image_gallery.git Tag camera2-lock-focus
or else run this command
git clone —branch camera2-lock-focus https://github.com/mobapptuts/recyclerview_image_gallery.git
CODE SAMPLES
Add some samples to reference the various camera states
private static final int STATE_PREVIEW = 0; private static final int STATE__WAIT_LOCK = 1;
In the CameraCaptureSession callback member override the members onCaptureCompleted & onCaptureFailed. The add a new method to the callback called process where if the state is “STATE_WAIT_LOCK” the auto focus state will be checked for focus lock.
private CameraCaptureSession.CaptureCallback mSessionCaptureCallback = new CameraCaptureSession.CaptureCallback() { private void process(CaptureResult result) { switch(mState) { case STATE_PREVIEW: // Do nothing break; case STATE__WAIT_LOCK: Integer afState = result.get(CaptureResult.CONTROL_AF_STATE); if(afState == CaptureRequest.CONTROL_AF_STATE_FOCUSED_LOCKED) { unLockFocus(); Toast.makeText(getApplicationContext(), "Focus Lock Successful", Toast.LENGTH_SHORT).show(); } break; } } @Override public void onCaptureStarted(CameraCaptureSession session, CaptureRequest request, long timestamp, long frameNumber) { super.onCaptureStarted(session, request, timestamp, frameNumber); } @Override public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) { super.onCaptureCompleted(session, request, result); process(result); } @Override public void onCaptureFailed(CameraCaptureSession session, CaptureRequest request, CaptureFailure failure) { super.onCaptureFailed(session, request, failure); Toast.makeText(getApplicationContext(), "Focus Lock Unsuccessful", Toast.LENGTH_SHORT).show(); } };
Create lockFocus & unLockFocus methods
private void lockFocus() { try { mState = STATE__WAIT_LOCK; mPreviewCaptureRequestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER, CaptureRequest.CONTROL_AF_TRIGGER_START); mCameraCaptureSession.capture(mPreviewCaptureRequestBuilder.build(), mSessionCaptureCallback, mBackgroundHandler); } catch (CameraAccessException e) { e.printStackTrace(); } } private void unLockFocus() { try { mState = STATE_PREVIEW; mPreviewCaptureRequestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER, CaptureRequest.CONTROL_AF_TRIGGER_CANCEL); mCameraCaptureSession.capture(mPreviewCaptureRequestBuilder.build(), mSessionCaptureCallback, mBackgroundHandler); } catch (CameraAccessException e) { e.printStackTrace(); } }
Call the lockFocus from the takePhoto method
public void takePhoto(View view) { lockFocus(); }