Manual Focus Distance in Android Camera2 API Not Applied Correctly Before Capturing Image

I’m working on an Android camera app using the android.hardware.camera2 API. I’m trying to set the manual focus distance using CaptureRequest.LENS_FOCUS_DISTANCE. While I can see from the logs that the focus distance is being applied, it only works correctly after I take a first picture and then take a second one (where it only gets applied for the second one) or change/move the slider.
Here’s the relevant code snippets:
StartCaameraPreview() method which is called in the CameraDevice.StateCallback onOpened callback:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>private void startCameraPreview() {
try {
SurfaceTexture surfaceTexture = textureView.getSurfaceTexture();
surfaceTexture.setDefaultBufferSize(previewSize.getWidth(), previewSize.getHeight());
repeatingRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
// Take full manual control of camera settings
if (isManualExposureSupported) {
repeatingRequestBuilder.set(CaptureRequest.CONTROL_AE_MODE, CameraMetadata.CONTROL_AE_MODE_OFF);
} else {
Log.d(TAG, "Camera's sensitivity settings cannot be set.");
}
if (isManualFocusSupported && !autoFocusEnabled) {
repeatingRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE, CameraMetadata.CONTROL_AF_MODE_OFF);
// Read lens focus distance range
minFocusDistance = cameraCharacteristics.get(CameraCharacteristics.LENS_INFO_MINIMUM_FOCUS_DISTANCE);
float maxFocusDistance = cameraCharacteristics.get(CameraCharacteristics.LENS_INFO_HYPERFOCAL_DISTANCE);
focusDistanceRange = maxFocusDistance - minFocusDistance;
// Set initial slider value and focus distance
if (manualFocusDistance != null) {
manualFocusSlider.setValue(manualFocusDistance);
repeatingRequestBuilder.set(CaptureRequest.LENS_FOCUS_DISTANCE, manualFocusDistance);
}
} else {
Log.d(TAG, "Camera's focus settings cannot be set to manual.");
}
Range<Integer> isoRange = cameraCharacteristics.get(CameraCharacteristics.SENSOR_INFO_SENSITIVITY_RANGE);
if (isoRange != null && isoValue != null) {
repeatingRequestBuilder.set(CaptureRequest.SENSOR_SENSITIVITY, isoValue);
}
previewSurface = new Surface(surfaceTexture);
repeatingRequestBuilder.addTarget(previewSurface);
cameraDevice.createCaptureSession(Arrays.asList(previewSurface, imageReader.getSurface()), new CameraCaptureSession.StateCallback() {
@Override
public void onConfigured(@NonNull CameraCaptureSession session) {
cameraCaptureSession = session;
Log.d(TAG, "Capture session configured");
// Update camera preview
updateCameraPreview();
captureCallback = new CameraCaptureSession.CaptureCallback() {
...
};
}
@Override
public void onConfigureFailed(@NonNull CameraCaptureSession session) {
// Handle configuration failure
}
}, null);
// new Handler().postDelayed(this::updateCameraPreview, 1000);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
</code>
<code>private void startCameraPreview() { try { SurfaceTexture surfaceTexture = textureView.getSurfaceTexture(); surfaceTexture.setDefaultBufferSize(previewSize.getWidth(), previewSize.getHeight()); repeatingRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW); // Take full manual control of camera settings if (isManualExposureSupported) { repeatingRequestBuilder.set(CaptureRequest.CONTROL_AE_MODE, CameraMetadata.CONTROL_AE_MODE_OFF); } else { Log.d(TAG, "Camera's sensitivity settings cannot be set."); } if (isManualFocusSupported && !autoFocusEnabled) { repeatingRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE, CameraMetadata.CONTROL_AF_MODE_OFF); // Read lens focus distance range minFocusDistance = cameraCharacteristics.get(CameraCharacteristics.LENS_INFO_MINIMUM_FOCUS_DISTANCE); float maxFocusDistance = cameraCharacteristics.get(CameraCharacteristics.LENS_INFO_HYPERFOCAL_DISTANCE); focusDistanceRange = maxFocusDistance - minFocusDistance; // Set initial slider value and focus distance if (manualFocusDistance != null) { manualFocusSlider.setValue(manualFocusDistance); repeatingRequestBuilder.set(CaptureRequest.LENS_FOCUS_DISTANCE, manualFocusDistance); } } else { Log.d(TAG, "Camera's focus settings cannot be set to manual."); } Range<Integer> isoRange = cameraCharacteristics.get(CameraCharacteristics.SENSOR_INFO_SENSITIVITY_RANGE); if (isoRange != null && isoValue != null) { repeatingRequestBuilder.set(CaptureRequest.SENSOR_SENSITIVITY, isoValue); } previewSurface = new Surface(surfaceTexture); repeatingRequestBuilder.addTarget(previewSurface); cameraDevice.createCaptureSession(Arrays.asList(previewSurface, imageReader.getSurface()), new CameraCaptureSession.StateCallback() { @Override public void onConfigured(@NonNull CameraCaptureSession session) { cameraCaptureSession = session; Log.d(TAG, "Capture session configured"); // Update camera preview updateCameraPreview(); captureCallback = new CameraCaptureSession.CaptureCallback() { ... }; } @Override public void onConfigureFailed(@NonNull CameraCaptureSession session) { // Handle configuration failure } }, null); // new Handler().postDelayed(this::updateCameraPreview, 1000); } catch (CameraAccessException e) { e.printStackTrace(); } } </code>
private void startCameraPreview() {
    try {
        SurfaceTexture surfaceTexture = textureView.getSurfaceTexture();
        surfaceTexture.setDefaultBufferSize(previewSize.getWidth(), previewSize.getHeight());

        repeatingRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);

        // Take full manual control of camera settings
        if (isManualExposureSupported) {
            repeatingRequestBuilder.set(CaptureRequest.CONTROL_AE_MODE, CameraMetadata.CONTROL_AE_MODE_OFF);
        } else {
            Log.d(TAG, "Camera's sensitivity settings cannot be set.");
        }

        if (isManualFocusSupported && !autoFocusEnabled) {
            repeatingRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE, CameraMetadata.CONTROL_AF_MODE_OFF);

            // Read lens focus distance range
            minFocusDistance = cameraCharacteristics.get(CameraCharacteristics.LENS_INFO_MINIMUM_FOCUS_DISTANCE);
            float maxFocusDistance = cameraCharacteristics.get(CameraCharacteristics.LENS_INFO_HYPERFOCAL_DISTANCE);
            focusDistanceRange = maxFocusDistance - minFocusDistance;

            // Set initial slider value and focus distance
            if (manualFocusDistance != null) {
                manualFocusSlider.setValue(manualFocusDistance);
                repeatingRequestBuilder.set(CaptureRequest.LENS_FOCUS_DISTANCE, manualFocusDistance);
            }
        } else {
            Log.d(TAG, "Camera's focus settings cannot be set to manual.");
        }

        Range<Integer> isoRange = cameraCharacteristics.get(CameraCharacteristics.SENSOR_INFO_SENSITIVITY_RANGE);
        if (isoRange != null && isoValue != null) {
            repeatingRequestBuilder.set(CaptureRequest.SENSOR_SENSITIVITY, isoValue);
        }

        previewSurface = new Surface(surfaceTexture);
        repeatingRequestBuilder.addTarget(previewSurface);

        cameraDevice.createCaptureSession(Arrays.asList(previewSurface, imageReader.getSurface()), new CameraCaptureSession.StateCallback() {
            @Override
            public void onConfigured(@NonNull CameraCaptureSession session) {
                cameraCaptureSession = session;

                Log.d(TAG, "Capture session configured");

                // Update camera preview
                updateCameraPreview();

                captureCallback = new CameraCaptureSession.CaptureCallback() {
                    ...
                };
            }

            @Override
            public void onConfigureFailed(@NonNull CameraCaptureSession session) {
                // Handle configuration failure
            }
        }, null);
        // new Handler().postDelayed(this::updateCameraPreview, 1000);
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }
}

updateCameraPreview():

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>private void updateCameraPreview() {
if (cameraDevice == null || repeatingRequestBuilder == null || cameraCaptureSession == null || previewSurface == null) {
Log.e(TAG, "cameraDevice objects have not been initialized yet");
return;
}
try {
repeatingRequestBuilder.addTarget(previewSurface);
cameraCaptureSession.setRepeatingRequest(repeatingRequestBuilder.build(), null, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
</code>
<code>private void updateCameraPreview() { if (cameraDevice == null || repeatingRequestBuilder == null || cameraCaptureSession == null || previewSurface == null) { Log.e(TAG, "cameraDevice objects have not been initialized yet"); return; } try { repeatingRequestBuilder.addTarget(previewSurface); cameraCaptureSession.setRepeatingRequest(repeatingRequestBuilder.build(), null, null); } catch (CameraAccessException e) { e.printStackTrace(); } } </code>
private void updateCameraPreview() {
    if (cameraDevice == null || repeatingRequestBuilder == null || cameraCaptureSession == null || previewSurface == null) {
        Log.e(TAG, "cameraDevice objects have not been initialized yet");
        return;
    }
    try {
        repeatingRequestBuilder.addTarget(previewSurface);
        cameraCaptureSession.setRepeatingRequest(repeatingRequestBuilder.build(), null, null);
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }
}

get Manual focus distance observer inside OnViewCreated callback:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>settingsViewModel.getManualFocusDistance().observe(getViewLifecycleOwner(), new Observer<Float>() {
@Override
public void onChanged(Float manualFocusDistance) {
CameraFragment.this.manualFocusDistance = manualFocusDistance;
if (isManualFocusSupported) {
if (repeatingRequestBuilder != null && !settingsViewModel.getAutoFocusEnabled().getValue()) {
repeatingRequestBuilder.set(CaptureRequest.LENS_FOCUS_DISTANCE, manualFocusDistance);
updateCameraPreview();
}
Range<Float> focusDistanceRange = getManualFocusDistanceRange(cameraCharacteristics);
// TODO: also applied it to startCameraPreview()
if (manualFocusDistance != null) {
manualFocusSlider.setValue(manualFocusDistance);
manualFocusSlider.setValueFrom(focusDistanceRange.getLower());
manualFocusSlider.setValueTo(focusDistanceRange.getUpper());
}
}
}
});
</code>
<code>settingsViewModel.getManualFocusDistance().observe(getViewLifecycleOwner(), new Observer<Float>() { @Override public void onChanged(Float manualFocusDistance) { CameraFragment.this.manualFocusDistance = manualFocusDistance; if (isManualFocusSupported) { if (repeatingRequestBuilder != null && !settingsViewModel.getAutoFocusEnabled().getValue()) { repeatingRequestBuilder.set(CaptureRequest.LENS_FOCUS_DISTANCE, manualFocusDistance); updateCameraPreview(); } Range<Float> focusDistanceRange = getManualFocusDistanceRange(cameraCharacteristics); // TODO: also applied it to startCameraPreview() if (manualFocusDistance != null) { manualFocusSlider.setValue(manualFocusDistance); manualFocusSlider.setValueFrom(focusDistanceRange.getLower()); manualFocusSlider.setValueTo(focusDistanceRange.getUpper()); } } } }); </code>
settingsViewModel.getManualFocusDistance().observe(getViewLifecycleOwner(), new Observer<Float>() {
        @Override
        public void onChanged(Float manualFocusDistance) {
            CameraFragment.this.manualFocusDistance = manualFocusDistance;

            if (isManualFocusSupported) {
                if (repeatingRequestBuilder != null && !settingsViewModel.getAutoFocusEnabled().getValue()) {
                    repeatingRequestBuilder.set(CaptureRequest.LENS_FOCUS_DISTANCE, manualFocusDistance);
                    updateCameraPreview();
                }
                Range<Float> focusDistanceRange = getManualFocusDistanceRange(cameraCharacteristics);
                // TODO: also applied it to startCameraPreview()
                if (manualFocusDistance != null) {
                    manualFocusSlider.setValue(manualFocusDistance);
                    manualFocusSlider.setValueFrom(focusDistanceRange.getLower());
                    manualFocusSlider.setValueTo(focusDistanceRange.getUpper());
                }
            }
        }
    });
    

manual focus slider onChangeListener:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>manualFocusSlider.addOnChangeListener(new Slider.OnChangeListener() {
@Override
public void onValueChange(@NonNull Slider slider, float value, boolean fromUser) {
if (minFocusDistance != null && focusDistanceRange != null) {
settingsViewModel.setManualFocusDistance(value);
} else {
Log.e(TAG, "Focus distance range for this camera has not been read yet");
}
}
});
</code>
<code>manualFocusSlider.addOnChangeListener(new Slider.OnChangeListener() { @Override public void onValueChange(@NonNull Slider slider, float value, boolean fromUser) { if (minFocusDistance != null && focusDistanceRange != null) { settingsViewModel.setManualFocusDistance(value); } else { Log.e(TAG, "Focus distance range for this camera has not been read yet"); } } }); </code>
manualFocusSlider.addOnChangeListener(new Slider.OnChangeListener() {
        @Override
        public void onValueChange(@NonNull Slider slider, float value, boolean fromUser) {
            if (minFocusDistance != null && focusDistanceRange != null) {
                settingsViewModel.setManualFocusDistance(value);
            } else {
                Log.e(TAG, "Focus distance range for this camera has not been read yet");
            }
        }
    });

The focus distance only seems to be applied correctly after I take a picture or change the slider in the preivew screen or for the requestBuilder. So it doesn’t apply correctly during the initial setup of the preview. However, the set ISO value seems to be applied correctly initially for my preview surface and also the first picture i capture.
So why does the manual focus distance not apply correctly during the initial preview setup and how might I ensure the focus distance is set correctly before capturing an image and during the preview?

Thanks a lot in advance!

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật