'How do you detect if an Android device has a camera?
I want to disable camera functionality in my app, if the device does not have a camera. However, I seem to have stumbled into a bug when doing so.
According to the official Android Developer docs, I can use hasSystemFeature() to detect device features at runtime, as shown below:
boolean hasAnyCamera = this.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY);
Log.i(LOG_TAG, "hasAnyCamera = " + hasAnyCamera);
boolean hasBackCamera = this.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA);
Log.i(LOG_TAG, "hasBackCamera = " + hasBackCamera);
However, I tried to create an emulator without a front-facing or back-facing camera, and it still returns true for both checks. Is there some other way that I can detect the camera in Android?
Relevant documentation:
Solution 1:[1]
After some research, it appears that this is a known bug, which has been unresolved for 10+ years now.
See: Emulator does not honour Camera support flag
It seems that the only know work-around is to detect the number of cameras using the Camera.getNumberOfCameras() method, which has been deprecated since Android 5.0.
boolean hasCamera = Camera.getNumberOfCameras() > 0;
Log.i(LOG_TAG, "hasCamera = " + hasCamera);
The above method seems to work on my emulator, despite the warning that it is deprecated.
Now according to the docs for Camera.getNumberOfCameras():
"The return value of [getNumberOfCameras()] might change dynamically if the device supports external cameras and an external camera is connected or disconnected."
So perhaps hasSystemFeature() always returns true, because the device might later have an external camera attached?
Solution 2:[2]
An emulator started by using a hardware configuration which enables or disables some features in runtime. It would be possible to add / change some configuration for your emulator.
I think, It is not removing camera hardware, just disables them. I created an emulator as you mentionned and there was no camera. When I changed the configuration I was able to use the camera. However, hasSystemFeature returned true for both situtation.
When you create an emulator, the settings you choose is written in hardware-qemu.ini for that AVD. You can find it in ~/.android/avd/YOUR_EMULATOR.avd/hardware-qemu.ini. You can get exact path in show on disk on Device Manager.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | ocos |

