From a315db3828e85d299bc5a4c280d516b5525413b0 Mon Sep 17 00:00:00 2001 From: Alex Ryltsov Date: Wed, 18 Dec 2024 09:01:40 +0200 Subject: [PATCH] bugfix: getSupportedFlashModes returns array empty in Android 14 SDK 34 #345 Changes: - implemented the fix to flip/switch between the main front and back cameras and avoid switching to additional cameras --- .../camera/preview/CameraActivity.java | 38 ++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/android/src/main/java/com/ahm/capacitor/camera/preview/CameraActivity.java b/android/src/main/java/com/ahm/capacitor/camera/preview/CameraActivity.java index b0554fe1..665ca277 100644 --- a/android/src/main/java/com/ahm/capacitor/camera/preview/CameraActivity.java +++ b/android/src/main/java/com/ahm/capacitor/camera/preview/CameraActivity.java @@ -427,6 +427,42 @@ public Camera getCamera() { return mCamera; } + /** + * Method to get the front camera id if the current camera is back and visa versa + * + * @return front or back camera id depending on the currently active camera + */ + private int getNextCameraId() { + int nextCameraId = 0; + + // Find the total number of cameras available + // NOTE: The getNumberOfCameras() method in Android's android.hardware.camera API returns the total + // number of cameras available on the device. The number might not be limited to just the front + // and back cameras because modern smartphones often come with more than two cameras. + // For example, devices might have: + // - a main (back) camera. + // - a wide-angle camera. + // - a telephoto camera. + // - a depth-sensing camera. + // - an ultrawide camera. + // - a macro camera. + // etc. + numberOfCameras = Camera.getNumberOfCameras(); + + int nextFacing = cameraCurrentlyLocked == Camera.CameraInfo.CAMERA_FACING_BACK ? Camera.CameraInfo.CAMERA_FACING_FRONT : Camera.CameraInfo.CAMERA_FACING_BACK; + + // Find the next ID of the camera to switch to (front if the current is back and visa versa) + Camera.CameraInfo cameraInfo = new Camera.CameraInfo(); + for (int i = 0; i < numberOfCameras; i++) { + Camera.getCameraInfo(i, cameraInfo); + if (cameraInfo.facing == nextFacing) { + nextCameraId = i; + break; + } + } + return nextCameraId; + } + public void switchCamera() { // check for availability of multiple cameras if (numberOfCameras == 1) { @@ -444,7 +480,7 @@ public void switchCamera() { Log.d(TAG, "cameraCurrentlyLocked := " + Integer.toString(cameraCurrentlyLocked)); try { - cameraCurrentlyLocked = (cameraCurrentlyLocked + 1) % numberOfCameras; + cameraCurrentlyLocked = getNextCameraId(); Log.d(TAG, "cameraCurrentlyLocked new: " + cameraCurrentlyLocked); } catch (Exception exception) { Log.d(TAG, exception.getMessage());