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 b0554fe..665ca27 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());