In my app, I'd like to use the camera, if the device has one. Are there any devices running android that do not have a camera? By including the following into my manifest:
<uses-feature android:name="android.hardware.camera" android:required="false"/>
then it's basically saying "I'll use a camera if one exists, but don't need one to run the app".
How could I check if a camera exists on the device, before attempting to use the Camera class?
This is what I'm using
import android.content.pm.PackageManager;
PackageManager pm = context.getPackageManager();
if (pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
}
All sorts of other fun things to test for are available too - the compass, is location available, is there a front facing camera:
http://developer.android.com/reference/android/content/pm/PackageManager.html
To find out how many cameras are available on your device, you can call:
import android.hardware.Camera;
int numCameras = Camera.getNumberOfCameras();
if (numCameras > 0) {
hasCamera = true;
}
Camera.getNumberOfCameras() is static, so it doesn't require actually connecting to a camera. This works since API 9.
Edit:
With the newer camera2 API, you can also call CameraManager.getCameraIdList(), which gives a list of the all the valid camera IDs, instead of just the count.
you should use this to find camera in your device
public static boolean isCameraAvailable(Context context) {
return context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY);
}
Camera.getNumberOfCameras() is deprecated. You can use:
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
public int getNumberOfCameras() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
try {
return ((CameraManager) getSystemService(Context.CAMERA_SERVICE)).getCameraIdList().length;
} catch (CameraAccessException e) {
Log.e("", "", e);
}
}
return Camera.getNumberOfCameras();
}
Use the PackageManager.hasSystemFeature() method for checking Camera :
private boolean checkCameraHardware(Context context) {
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
Source: https://developer.android.com/guide/topics/media/camera.html#custom-camera
by following way we can check does device has camera or not.
/** Check if this device has a camera */
public static boolean checkCameraHardware(Context context) {
if (context.getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA))
{
return true;
}
else if(context.getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA_FRONT))
{
return true;
}
else {
return false;
}
}
try this
For front camera
Context context = this;
PackageManager packageManager = context.getPackageManager();
if (packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA_FRONT)) {
Utils.makeAlertDialog(context, "Has Front Camera ?", "YES");
} else {
Utils.makeAlertDialog(context, "Has Front Camera ?", "NO");
}
for back camera
Context context = this;
PackageManager packageManager = context.getPackageManager();
if (packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
Utils.makeAlertDialog(context, "Has back Camera ?", "YES");
} else {
Utils.makeAlertDialog(context, "Has back Camera ?", "NO");
}
Try this :
/** Check if this device has a camera */
private boolean checkCameraHardware(Context context) {
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
from : http://developer.android.com/guide/topics/media/camera.html
As per Android documentation :
/** Check if this device has a camera */
private boolean checkCameraHardware(Context context) {
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
Refer more about the camera API : https://developer.android.com/guide/topics/media/camera.html#detect-camera
If you are using Android 2.3, there are some APIs that you can check your camera status, such as the number of cameras (front and back)
it is better to check ANY camera on the device since it could be external camera as well
packageManager.hasSystemFeature(FEATURE_CAMERA_ANY)
Documentation:
Feature for getSystemAvailableFeatures and hasSystemFeature: The
device has at least one camera pointing in some direction, or can
support an external camera being connected to it.
As per the documentation, you have to use Package Manager to check if Camera is available on the device or not
In Java:
final boolean isCameraAvailable = getPackageManager().hasSystemFeature(FEATURE_CAMERA);
In Kotlin:
val isCameraAvailable = packageManager.hasSystemFeature(FEATURE_CAMERA)
I found in android tv boxes where you can plug and play usb camera a number of times. At some point of time, The camera service starts saying that it detected one camera in the system while no camera is connected to the system. This happens when you plug in/out the camera a number of times. To fix that, I found this solution working:
//under oncreate:
//cameraManager = ((CameraManager) getSystemService(Context.CAMERA_SERVICE));
public int getNumberOfCameras() {
int count_ = 0;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
try {
count_ = cameraManager.getCameraIdList().length;
if(count_==1)
{
try {
cameraManager.getCameraCharacteristics(cameraManager.getCameraIdList()[0]);
}catch (Exception e)
{
count_ = 0;
}
}
} catch (Exception e) {
//e.printStackTrace();
}
}
else {
count_ = Camera.getNumberOfCameras();
}
return count_;
}
One line solution:
public static boolean hasCamera(Context context) {
return context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA);
}
Put this method in your Utils.java project class.
I've not tried it, but:
private android.hardware.Camera mCameraDevice;
try {
mCameraDevice = android.hardware.Camera.open();
} catch (RuntimeException e) {
Log.e(TAG, "fail to connect Camera", e);
// Throw exception
}
May be what you need.
Related
I have been working on Custom SurfaceView Camera. I need to work with front camera as my application takes user's selfie.
For that I have checked a for whether front camera is available using below code.
public boolean checkFrontCamera() {
int numCameras = Camera.getNumberOfCameras();
for (int i = 0; i < numCameras; i++) {
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(i, info);
if (CameraSource.CAMERA_FACING_FRONT == info.facing) {
return true;
}
}
return false;
}
Its working fine if device has both the camera, and it returns true. But if device has only one camera, this method always returns false as info.facing is 0 in this case and for the same in this code CameraSource.CAMERA_FACING_FRONT is 1.
for Camera, I have used gms vision library. Below code is for camera source.
CameraSource mCameraSource = new CameraSource.Builder(context, detector)
.setRequestedPreviewSize(640, 480)
.setFacing(CameraSource.CAMERA_FACING_FRONT)
.setRequestedFps(30.0f)
.build();
Here I need to pass camera facing params.
Please provide if any other alternative. All solutions are welcomed.
Well you can use this method, which returns the camera object
private Camera getCameraInstance() {
Camera c = null;
try {
if (Camera.getNumberOfCameras() >= 2) {
//Front facing camera
c = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT);
} else {
// only has one camera (Rear)
c = Camera.open();
}
} catch (Exception e) {
// Camera is not available (in use or does not exist)
}
return c; // returns null if camera is unavailable
}
I am trying to make a torchlight app but I am not able to turn it on properly. I have used the following logic to turn it on. Please let me know where I am going wrong. When I run this on my android phone it runs properly but the flashlight doesn't start.
if (count[0] == 0) {
count[0] = 1;
((TransitionDrawable) imageView.getDrawable()).startTransition(3000);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
CameraManager camManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
String cameraId = null; // Usually back camera is at 0 position.
try {
cameraId = camManager.getCameraIdList()[0];
camManager.setTorchMode(cameraId, true); //Turn ON
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
} else {
count[0] = 0;
((TransitionDrawable) imageView.getDrawable()).reverseTransition(3000);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
CameraManager camManager1 = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
String cameraId = null; // Usually back camera is at 0 position.
try {
cameraId = camManager1.getCameraIdList()[0];
camManager1.setTorchMode(cameraId, false); //Turn ON
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
}
The code you have written is fully functional on Android Marshmallow+.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
This line checks for what version of Android you are running the app on. It executes the code within the if block only on Android version 6+ (API level 23+).
You need to add the else part with an older way of turning the flashlight on like this method: How to turn on camera flash light programmatically in Android?
My app has functionality that requires a rear camera. Whether there is a front camera or not is irrelevant to my needs. Putting together a robust routine to detect whether or not a rear camera exists, in all circumstances, is proving tricky. For example, a user with an HTC Evo 3D has complained that the app says there's no rear camera (there clearly is), and I've had a number of similar complaints from other users.
This is a tricky thing to test, as despite having a number of devices I don't have a device with only a front camera, such as the Nexus 7, or any of the models mentioned by the users.
Here's what I have, and this was taken from code on other answers on this site:
boolean rearCameraFound = false;
if(BUILD_VERSION > 8){
int cameraCount = 0;
Camera cam = null;
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
cameraCount = Camera.getNumberOfCameras();
for ( int camIdx = 0; camIdx < cameraCount; camIdx++ ) {
Camera.getCameraInfo( camIdx, cameraInfo );
if ( cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK ) {
try {
cam = Camera.open( camIdx );
Log.d("TAG", "Rear camera detected");
rearCameraFound = true;
} catch (RuntimeException e) {
Log.e("TAG", "Camera failed to open: " + e.getLocalizedMessage());
}
}
if ( cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT ) {
Log.d("TAG", "Front camera detected");
}
}
return rearCameraFound;
}else{
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
I've now replaced this code with this much simpler version:
PackageManager pm = context.getPackageManager();
return pm.hasSystemFeature(PackageManager.FEATURE_CAMERA);
However, I don't know what would happen on the Nexus 7 for example, with only a front camera. Would this return true?
I'm looking for code that will tell me for sure if there's a rear camera or not!
Nexus 7 (which has only one frontal camera) returns false to FEATURE_CAMERA, Instead of it, you can use FEATURE_CAMERA_FRONT. Check out this discussion.
Now, by using the above, you could make sure that there is atleast one camera. So now, you can check the number of camera's present in the phone, if it is greater than one, then there will be surely a rear camera.
import android.hardware.Camera;
int numCameras = Camera.getNumberOfCameras();
if (numCameras > 1) {
rearCamera = true;
}
This is quite tricky. But that's all, I can now think of. Just give it a try.
Use this snippet. Note this only works for API 9 or higher.
private static boolean checkCameraFacing(final int facing) {
if (getSdkVersion() < Build.VERSION_CODES.GINGERBREAD) {
return false;
}
final int cameraCount = Camera.getNumberOfCameras();
CameraInfo info = new CameraInfo();
for (int i = 0; i < cameraCount; i++) {
Camera.getCameraInfo(i, info);
if (facing == info.facing) {
return true;
}
}
return false;
}
public static boolean hasBackFacingCamera() {
final int CAMERA_FACING_BACK = 0;
return checkCameraFacing(CAMERA_FACING_BACK);
}
public static boolean hasFrontFacingCamera() {
final int CAMERA_FACING_BACK = 1;
return checkCameraFacing(CAMERA_FACING_BACK);
}
public static int getSdkVersion() {
return android.os.Build.VERSION.SDK_INT;
}
And this is no need to open the camera.
For front camera
Context context = this; //If its Activity
// Context context=getActivity(); If its a Fragment
PackageManager packageManager = context.getPackageManager();
if (packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA_FRONT)) {
Log.i("CameraLog", "Front Camera Available");
} else {
Log.i("CameraLog", "No Front Camera Available");
}
for back camera
Context context = this; //If its an Activity
// Context context=getActivity(); If its a fragments
PackageManager packageManager = context.getPackageManager();
if (packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
Log.i("CameraLog", "Back Camera is Available");
} else {
Log.i("CameraLog", "No Back Camera Available");
}
If device has one camera only, it can have back camera only, or the front camera only, first check if back camera exists:
Check if front camera exists, but devices with two cameras has front camera obviously
Check if device has one camera only, but it can have back or front camera
Final result: If device has the front camera and it has one camera only, back camera no exists
private boolean backCameraExists() {
boolean isFrontExists = getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FRONT);
if (isFrontExists && (Camera.getNumberOfCameras()<2)) {
return false;
}
return true;
}
To check whether camera is running or not i am writing these code
ActivityManager actvityManager = (ActivityManager)this.getSystemService(ACTIVITY_SERVICE);
String packageName = actvityManager.getRunningTasks(1).get(0).topActivity.getPackageName();
if(packageName.equals("android.hardware.camera")||packageName.equals("com.android.camera")){
Camera_status = "STATUS_ON";
System.out.println("===on===");
}else{
Camera_status = "STATUS_OFF";
System.out.println("====off====");
}
By using this, i am able to get correct result in android emulator but while testing In real device i an not able to get the correct result.As per the answer posted here by CommonsWare,i think he is correct.So friends may i know how to get the camera on/off status programmatically.
Try This its working!!!
Camera _camera;
boolean qOpened = false;
try {
_camera=Camera.open();
qOpened=(_camera!=null);
if(qOpened){
Camera_status = "STATUS_OFF";
}else{
System.out.println("==nothing to do====");
}
} catch (Exception e) {
Camera_status = "STATUS_ON";
System.out.println("=====Camera running=====");
}
How to detect no of camera's available in android device? and also if the device has front camera how to use it?
What I would suggest is similar to doc_180's answer, but should be able to detect both front and back facing cameras even for Froyo, though if I'm not mistaken, Froyo never supported front-facing cameras, so you'll always get a false response for frontCam on Froyo.
PackageManager pm = getPackageManager();
boolean frontCam, rearCam;
//Must have a targetSdk >= 9 defined in the AndroidManifest
frontCam = pm.hasSystemFeature(PackageManager.FEATURE_CAMERA_FRONT);
rearCam = pm.hasSystemFeature(PackageManager.FEATURE_CAMERA);
EDIT: Just realized this is a really, really old question. Oh well, hopefully it helps someone in the future.
Use packagemanager to check if the device supports the Intent. In this case Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
public static boolean isIntentAvailable(Context context, String action) {
final PackageManager packageManager = context.getPackageManager();
final Intent intent = new Intent(action);
List<ResolveInfo> list =
packageManager.queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
CameraInfo cameraInfo = new CameraInfo();
for (int i = 0; i < numberOfCameras; i++) {
Camera.getCameraInfo(i, cameraInfo);
if (cameraInfo.facing == CameraInfo.CAMERA_FACING_FRONT) {
}
}
The quickest way I've found to check if a (backfacing) camera exists is to check if Camera.open() returns null.
Camera cam = Camera.open();
if(null == cam){
//no camera exists
}
This should be available for earlier versions of android as well.
you can use this static method if you just want to know how many cameras there are:
Camera.getNumberOfCameras(); (api 9)
/** Check if this device has a camera */
private boolean checkCameraHardware(Context context) {
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
I am using this method to get the count of the available camera
public int getCameraCount(){
CameraManager manager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
try {
String[] strings = manager.getCameraIdList();
return strings.length;
} catch (CameraAccessException e) {
e.printStackTrace();
return 0;
}
}
Try this, this worked for me in a Moto RAZR HD:
public static Camera open (int cameraId)
Example usage:
mCamera = Camera.open(1);