3

I want to check if a device has any cameras before trying to open a qr code reader.

I have the following code:

 public boolean checkDeviceCompatibility() {

PackageManager pm = context.getPackageManager();

if (pm.hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY)) {
    if (pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
    return true;
    } else {
    // use front camera
    Toast.makeText(
        context,
        "This device does not have a back camera so it has automatically reverted to the front camera",
        Toast.LENGTH_SHORT).show();
    return true;
    }
} else {
    util.displayErrorDialog(
        context,
        "This device does not have any cameras and therefore cannot make use of the QR Code feature.");
    return false;
}
}

But now if I run this code in debug mode on my galaxy S3 with two cameras. the first if statement is returned false.

Why could this be?

Zapnologica
  • 22,170
  • 44
  • 158
  • 253
  • check [this thread](http://stackoverflow.com/questions/22652189/hassystemfeaturepackagemanager-feature-camera-returns-true-for-device-with-no/25439559#25439559) hope you find it useful here. – Yogesh D Oct 31 '14 at 09:00

2 Answers2

6

FEATURE_CAMERA_ANY was added in Android 4.2. hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY) should return false for any pre-4.2 device. If your S3 is still on 4.1, that would explain your problem.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
3

To make it clear.

FEATURE_CAMERA_ANY was added to Android 4.2 ( API-17): Android - developers.

code:

public static boolean hasCamera(Context context) {
    return context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY);
}

Note that using this code will return false if device under version 4.2:

Then you should know that there is a bug with emulator when use FEATURE_CAMERA_ANY feature (with android 4.2 and above). see: Emulator does not honour Camera support flag

Thats why Im still using old way even its deprecated:

public static boolean hasCamera() {
    return android.hardware.Camera.getNumberOfCameras() > 0;
}
Maher Abuthraa
  • 17,493
  • 11
  • 81
  • 103
  • 3
    Seems that this is the best way. For example packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA) gives FALSE on Nexus 7 Kit-Kat 4.4 with Front camera which is a bug since camera is present on the device – Kirill Karmazin Mar 22 '17 at 21:05