How to open usb camera in android using android.hardware.camera.external - android

I have connected a usb camera and want open and take picture.
I am trying to figure how to use "android.hardware.camera.external" feature for accessing that camera.
The "manager.getCameraIdList();" returns count of 2 camera(for front and back) and not the usb camera that is connected.

For me works the next config for USB Cameras with official API:
Camera (old API)
On some china devices, Camera.CameraInfo.CAMERA_FACING_FRONT works, but some times your should force to camIdx to 0.
public static Camera getCameraInstance() {
Camera c = null;
try {
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
int cameraCount = Camera.getNumberOfCameras();
for (int camIdx = 0; camIdx < cameraCount; camIdx++) {
Camera.getCameraInfo(camIdx, cameraInfo);
Log.i(TAG, "[Camera] try to open camera camIdx:" + camIdx);
if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
try {
c = Camera.open(camIdx);
mCameraIdx = camIdx;
Log.i(TAG, "[Camera] camIdx:" + camIdx);
} catch (RuntimeException e) {
Log.e(TAG, "[Camera] failed to open: " + e.getLocalizedMessage());
}
}
}
if (c == null) {
Log.i(TAG, "[Camera] forcing open camera with camIdx 0");
c = Camera.open(0); // force because FACING_FRONT not found
mCameraIdx = 0;
}
} catch (Exception e) {
Logger.e("TAG", "[Camera] Open camera failed: " + e);
}
return c;
}
Camera2 (new API)
Similar for Camera2 API:
public String getCamera(CameraManager manager) {
String cameraIndex = "0";
try {
for (String cameraId : manager.getCameraIdList()) {
CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
Logger.d(TAG, "cameraId " + cameraId);
int cOrientation = characteristics.get(CameraCharacteristics.LENS_FACING);
if (cOrientation != CAMERACHOICE) {
cameraIndex = cameraId;
}
}
} catch (CameraAccessException e) {
e.printStackTrace();
}
return cameraIndex;
}
But in my experience some Android ROM implementations are really bad (sometimes custom hardware or china hardware) then it not works. In some situations you should be use libuvc driver fore some USB Cameras: https://github.com/saki4510t/UVCCamera

There's currently (as of Android O) no common USB camera support on Android devices via the standard camera API.
Some Android manufacturers do have their own support for USB cameras, but it's hard to know what devices do and what don't.

Related

Check custom front camera availibility

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
}

Why is the camera flash not turning on and the CameraAccessException class is underlined red?

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?

Switch front and back camera2 in android

I am creating a camera in android using android.hardware.camera2...
I referred to this link
But, I do not know how to switch front camera and back camera.
Please give a advice!
First of all get the list of camera Ids from device
We can use CameraManager to iterate all the cameras that are available in the system, each with a designated cameraId. Using the cameraId, we can get the properties of the specified camera device. Those properties are represented by class CameraCharacteristics. Things like "is it front or back camera", "output resolutions supported" can be queried there.
CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
try {
return manager.getCameraIdList();
} catch (CameraAccessException e) {
return null;
}
Now if you want to open Front camera
CameraCharacteristics characteristics
= manager.getCameraCharacteristics(cameraId);
Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING);
if (facing != null && facing == CameraCharacteristics.LENS_FACING_FRONT) {
//Do your code here (open Camera with Camera ID)
}
This is another method directly which return directly CameraId .
String getFrontFacingCameraId(CameraManager cManager){
for(final String cameraId : cManager.getCameraIdList()){
CameraCharacteristics characteristics = cManager.getCameraCharacteristics(cameraId);
int cOrientation = characteristics.get(CameraCharacteristics.LENS_FACING);
if(cOrientation == CameraCharacteristics.LENS_FACING_FRONT) return cameraId;
}
return null;
}
For More Information about Camera2 Api you can see Here

Detecting lack of rear camera

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;
}

How do I open the "front camera" on the Android platform?

More generally, if a device has more than one embedded camera,
is there a way to initialize one of them in particular?
I didn't find it in Android reference documentation:
https://developer.android.com/reference/android/hardware/Camera.html
https://developer.android.com/reference/android/hardware/camera2/package-summary.html
https://developer.android.com/reference/android/hardware/camera2/CameraManager.html
Samsung SHW-M100S has two cameras. If there is no reference to use two cameras, any idea how Samsung did...?
private Camera openFrontFacingCameraGingerbread() {
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_FRONT) {
try {
cam = Camera.open(camIdx);
} catch (RuntimeException e) {
Log.e(TAG, "Camera failed to open: " + e.getLocalizedMessage());
}
}
}
return cam;
}
Add the following permissions in the AndroidManifest.xml file:
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" android:required="false" />
<uses-feature android:name="android.hardware.camera.front" android:required="false" />
Note: This feature is available in Gingerbread(2.3) and Up Android Version.
All older answers' methods are deprecated by Google (supposedly because of troubles like this), since API 21 you need to use the Camera 2 API:
This class was deprecated in API level 21. We recommend using the new
android.hardware.camera2 API for new applications.
In the newer API you have almost complete power over the Android device camera and documentation explicitly advice to
String[] getCameraIdList()
and then use obtained CameraId to open the camera:
void openCamera(String cameraId, CameraDevice.StateCallback callback, Handler handler)
99% of the frontal cameras have id = "1", and the back camera id = "0"
according to this:
Non-removable cameras use integers starting at 0 for their
identifiers, while removable cameras have a unique identifier for each
individual device, even if they are the same model.
However, this means if device situation is rare like just 1-frontal -camera tablet you need to count how many embedded cameras you have, and place the order of the camera by its importance ("0"). So CAMERA_FACING_FRONT == 1 CAMERA_FACING_BACK == 0, which implies that the back camera is more important than frontal.
I don't know about a uniform method to identify the frontal camera on all Android devices. Simply said, the Android OS inside the device can't really find out which camera is exactly where for some reasons: maybe the only camera hardcoded id is an integer representing its importance or maybe on some devices whichever side you turn will be .. "back".
Documentation: https://developer.android.com/reference/android/hardware/camera2/package-summary.html
Explicit Examples: https://github.com/googlesamples/android-Camera2Basic
For the older API (it is not recommended, because it will not work on modern phones newer Android version and transfer is a pain-in-the-arse). Just use the same Integer CameraID (1) to open frontal camera like in this answer:
cam = Camera.open(1);
If you trust OpenCV to do the camera part:
Inside
<org.opencv.android.JavaCameraView
../>
use the following for the frontal camera:
opencv:camera_id="1"
As of Android 2.1, Android only supports a single camera in its SDK. It is likely that this will be added in a future Android release.
To open the back camera:-
val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
startActivityForResult(cameraIntent, REQUEST_CODE_CAMERA)
To open the front camera:-
val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
when {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1 && Build.VERSION.SDK_INT < Build.VERSION_CODES.O -> {
cameraIntent.putExtra("android.intent.extras.CAMERA_FACING", CameraCharacteristics.LENS_FACING_FRONT) // Tested on API 24 Android version 7.0(Samsung S6)
}
Build.VERSION.SDK_INT >= Build.VERSION_CODES.O -> {
cameraIntent.putExtra("android.intent.extras.CAMERA_FACING", CameraCharacteristics.LENS_FACING_FRONT) // Tested on API 27 Android version 8.0(Nexus 6P)
cameraIntent.putExtra("android.intent.extra.USE_FRONT_CAMERA", true)
}
else -> cameraIntent.putExtra("android.intent.extras.CAMERA_FACING", 1) // Tested API 21 Android version 5.0.1(Samsung S4)
}
startActivityForResult(cameraIntent, REQUEST_CODE_CAMERA)
I could not make it work for API 28 and above. Also, opening the front camera directly is not possible in some devices(depends on the manufacturer).
public void surfaceCreated(SurfaceHolder holder) {
try {
mCamera = Camera.open();
mCamera.setDisplayOrientation(90);
mCamera.setPreviewDisplay(holder);
Camera.Parameters p = mCamera.getParameters();
p.set("camera-id",2);
mCamera.setParameters(p);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
For API 21 (5.0) and later you can use the CameraManager API's
try {
String desiredCameraId = null;
for(String cameraId : mCameraIDsList) {
CameraCharacteristics chars = mCameraManager.getCameraCharacteristics(cameraId);
List<CameraCharacteristics.Key<?>> keys = chars.getKeys();
try {
if(CameraCharacteristics.LENS_FACING_FRONT == chars.get(CameraCharacteristics.LENS_FACING)) {
// This is the one we want.
desiredCameraId = cameraId;
break;
}
} catch(IllegalArgumentException e) {
// This key not implemented, which is a bit of a pain. Either guess - assume the first one
// is rear, second one is front, or give up.
}
}
}
With the release of Android 2.3 (Gingerbread), you can now use the android.hardware.Camera class to get the number of cameras, information about a specific camera, and get a reference to a specific Camera. Check out the new Camera APIs here.
build.gradle
dependencies {
compile 'com.google.android.gms:play-services-vision:9.4.0+'
}
Set View
CameraSourcePreview mPreview = (CameraSourcePreview) findViewById(R.id.preview);
GraphicOverlay mGraphicOverlay = (GraphicOverlay) findViewById(R.id.faceOverlay);
CameraSource mCameraSource = new CameraSource.Builder(context, detector)
.setRequestedPreviewSize(640, 480)
.setFacing(CameraSource.CAMERA_FACING_FRONT)
.setRequestedFps(30.0f)
.build();
mPreview.start(mCameraSource, mGraphicOverlay);
Camera camera;
if (Camera.getNumberOfCameras() >= 2) {
//if you want to open front facing camera use this line
camera = Camera.open(CameraInfo.CAMERA_FACING_FRONT);
//if you want to use the back facing camera
camera = Camera.open(CameraInfo.CAMERA_FACING_BACK);
}
try {
camera.setPreviewDisplay("your surface holder here");
camera.startPreview();
} catch (Exception e) {
camera.release();
}
/* This is not the proper way, this is a solution for older devices that run Android 4.0 or older. This can be used for testing purposes, but not recommended for main development. This solution can be considered as a temporary solution only. But this solution has helped many so I don't intend to delete this answer*/
I found this works nicely.
fun frontCamera(context: Context): Int {
val cameraManager = context.getSystemService(Context.CAMERA_SERVICE) as CameraManager
return cameraManager.cameraIdList
.find { id ->
cameraManager.getCameraCharacteristics(id)[LENS_FACING] == LENS_FACING_FRONT
}?.toInt() ?: 0
}

Categories

Resources