How to detect if front camera is available in android?

Viewed 5164

Actually i'm having some issues in my app,

Like i have a button that open front camera and skan a waiter badge but the problem comes when i try to check if a device has the camera and if it hasn't i just hide that buttons.

But i have a device that use the front camera as QR Scanner so it's not really a camera that can be used so the app crash when i try to click that button.

So the question is how can i handle and check if not only the camera exists but even if it works?

3 Answers

Use this method to detect whether devices has a front camera or not.

private boolean hasFrontCamera() {
    Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
    int numberOfCameras = Camera.getNumberOfCameras();
    for (int i = 0; i < numberOfCameras; i++) {
        Camera.getCameraInfo(i, cameraInfo);
        if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
            return true;
        }
    }
    return false;
}

Android Pie adds more features for enumerating cameras:

Apps running on Android 9 devices can discover every available camera by calling getCameraIdList(). An app should not assume that the device has only a single back camera or only a single front camera.

For example, if your app has a button to switch between the front and back cameras, there may be more than one front or back camera to choose from. You should walk the camera list, examine each camera's characteristics, and decide which cameras to expose to the user.

You can check if front camera is available in a device by using the PackageManager hasSystemFeature() function

private boolean checkCameraHardware(Context context) {
        if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FRONT)){
            // this device has a camera
            return true;
        } else {
            // no camera on this device
            return false;
        }
    }
Related