How to check if camera is opened by any application - android

Is there any way to check if the camera is open or not? I don't want to open the camera, I just want to check its status.

If your device API version is higher than 21, CameraManager.AvailabilityCallback might be a good choice.
You need to first obtain the camera manager of the system with the following code:
CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
Then, you need to register the AvailabilityCallback:
CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
manager.registerAvailabilityCallback(new CameraManager.AvailabilityCallback() {
#Override
public void onCameraAvailable(String cameraId) {
super.onCameraAvailable(cameraId);
//Do your work
}
#Override
public void onCameraUnavailable(String cameraId) {
super.onCameraUnavailable(cameraId);
//Do your work
}
}, yourHandler);
}
This works better if API version is higher than 21. You can refer to CameraManager, CameraManager.AvailabilityCallback, and the whole package
Trying to open the camera to check if exception is thrown works good if API level is lower than 23. In API level 23, camera service is different than before, from the official docs:
Access to camera subsystem resources, including opening and configuring a camera device, is awarded based on the “priority” of the client application process. Application processes with user-visible or foreground activities are generally given a higher-priority, making camera resource acquisition and use more dependable.
Active camera clients for lower priority apps may be “evicted” when a higher priority application attempts to use the camera. In the deprecated Camera API, this results in onError() being called for the evicted client. In the Camera2 API, it results in onDisconnected() being called for the evicted client.
We can see that in API 23 or higher, trying to open the camera used by other app/process will seize the camera from app/process which was using it, instead of getting RuntimeException.

You can check it using method Camera.open(cameraId).
Creates a new Camera object to access a particular hardware camera. If the same camera is opened by other applications, this will throw a RuntimeException.
Throws
RuntimeException
If opening the camera fails (For Example, if the camera is in use by another process or device policy manager has disabled the camera).
Update:
Example:
public boolean isCameraUsebyApp() {
Camera camera = null;
try {
camera = Camera.open();
} catch (RuntimeException e) {
return true;
} finally {
if (camera != null) camera.release();
}
return false;
}
You can use this method to use as Paul suggested but keep this thing in mind that this method first acquire the camera.
If its acquire successfully then its mean that no other application is using this camera and don't forgot to release it again otherwise you will not able to acquire it again.
Its its throws RuntimeException it means that camera is in use by another process or device policy manager has disabled the camera.

Looking into the source code of Camera, its JNI counterpart, and finally the native code for connecting a camera with the service, it appears that the only way of determining if the camera is in use is directly through the result of Camera::connect(jint).
The trouble is that this native code is only accessible through the JNI function android_hardware_Camera_native_setup(JNIEnv*, jobject, jobject, jint), which sets up the camera for use when creating the Camera instance from Java in new Camera(int).
In short, it doesn't seem possible. You'll have to attempt to open the camera, and if it fails, assume it is in use by another applicaiton. E.g.:
public boolean isCameraInUse() {
Camera c = null;
try {
c = Camera.open();
} catch (RuntimeException e) {
return true;
} finally {
if (c != null) c.release();
}
return false;
}
To better understand the underlying flow of camera's native code, see this thread.

Related

Access denied finding property "camera.hal1.packagelist"

While using camera in service mobile screen is getting un-touchable(locked by transparent window )
and only below error is occuring
Access denied finding property "camera.hal1.packagelist"
what will be the reason and its solution?
Please help..
I was working with the OpenCV tutorial code for camera app on android. I encountered the same error, and after looking at the answers I indeed missed one permission.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Although the app doesn't save any data externally, without this permission, the access denied error occurs.
Hope it helps.
I got the same error in my app, i was using surface view and had it weight set to zero. I changed it back to 1 and the error got resolved. Do check your xml code, it may help.
I had the same problem with the Camera 1 API on my Test device "LG V30". I found out, that this message (Access denied finding property "camera.hal1.packagelist") appeared when I opened the camera like this:
int numberOfCameras = Camera.getNumberOfCameras();
CameraInfo cameraInfo = new CameraInfo();
for (int i = 0; i < numberOfCameras; i++) {
Camera.getCameraInfo(i, cameraInfo);
if (cameraInfo.facing == CameraInfo.CAMERA_FACING_BACK) {
camera = Camera.open(i);
cameraId = i;
}
}
Important is, that this only happened for the LG V30, which has 2 back cameras (numberOfCameras=3).
After some testing I found out, that this works for this device:
/** A safe way to get an instance of the Camera object. */
public static Camera getCameraInstance(){
Camera c = null;
try {
c = Camera.open(); // attempt to get a Camera instance
}
catch (Exception e){
// Camera is not available (in use or does not exist)
}
return c; // returns null if camera is unavailable
}
The example code above will access the first, back-facing camera on a device with more than one camera. Here you can find a detailed description.
Please see if you asking for the Camera permission from the user.
Just specifying the permission in manifest is not gonna work above a certain Android level.
This will solve your problem.
How to ask for permission follow this link.
about Access denied finding property like error
less possible reason: lack related user permission
which
should added related config
<uses-permission android:name="android.permission.xxx"/>
when running app, first popup window for grant related permission, user self should Accept it
to give/grant the permission to app
most possible reason = probably:
cause by (previous log, you can see it logcat) the warning log:
type=1400 audit(xxx): avc: denied { xxx } for name=xxx dev=xxx ino=xxx scontext=xxx tcontext=xxx tclass=xxx permissive=0
how to fix avc: denied error ?
Simple:
refer offical doc Validating SELinux | Android Open Source Project try use audit2allow and related tool to fix.
Detailed:
refer my another post's anwser
My problem was for using Camera in android versions higher than API 23, I made two implementations.
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
camera = Camera.open();
parameters = camera.getParameters();
camera.startPreview();
}
...
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
CameraManager cameraManager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
try {
String cameraId = cameraManager.getCameraIdList()[0];
cameraManager.setTorchMode(cameraId, true);
} catch (Exception e) {
e.printStackTrace();
}
} else {
parameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(parameters);
}
For more information there is Camera, Camera2 and CameraX source https://developer.android.com/training/camera/choose-camera-library

Reasons why Android camera unavailable

I using android android.hardware.Camera class to capture image. For initialization I use following code.
Camera cam = null;
try {
cam = Camera.open();
} catch (Exception e) {
e.printStackTrace();
// camera unavailable
}
return cam;
I am interesting in catch block. For example, torch app is running at the moment of initialization. So Camera.open() throw RuntimeException with message Fail to connect to camera service.
Here is exception:
Is it possible to know the reason why camera is unavailable? I want to guide user how to fix this, for example show a dialog: "dude, turn off your torch".
If it's not possible, then in which cases camera could be blocked? I just will show user dialog with general instruction what he could do, for example: 1. turn off torch. 2. Close all camera app 3. Fed your cat etc.

android java lang runtimeexception fail to connect to camera service

I am currently working on Flashlight On/OFF. I am getting this error java.lang.RuntimeException: Fail to connect to camera service I don't know why this error is occurring. I referred to many solutions but my problem was still not solved. When flashlight is on, the error does not occur but when the flashlight is off then the error occurs.
My Code Main Code.
My Manifest permission:
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus"/>
I had the same issue that none of the answers here solved, so after solving it I am adding my way of solving it. This applies to new android versions that support setting permissions per app (since Marshmallow, 6.0). The permission for camera could be disabled and should be enabled from the app settings.
Settings -> Apps -> [Your App] -> Permissions
More info about this here: http://developer.android.com/training/permissions/requesting.html
I also saw this error:
java.lang.RuntimeException: Fail to connect to camera service
while experimenting with a flashlight app. Turns out that I was a bit sloppy with my permissions and copied them into the body of the application block in the manifest.xml file. So you REALLY need to obey the syntax as documented in:
http://developer.android.com/guide/topics/manifest/manifest-element.html
Otherwise the app will fail with service connection failure on the Camera.open() call. It should look like this based on your permissions in the question:
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus"/>
<application
Make sure your permission and feature list is contained only in the manifest section, and not buried in the application section!
try this...
static Camera camera = null;
declare it on top.
try{
if(clickOn == true) {
clickOn = false;
camera = Camera.open();
Parameters parameters = camera.getParameters();
parameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(parameters);
camera.startPreview();
remoteViews.setViewVisibility(R.id.button1, View.GONE);
remoteViews.setViewVisibility(R.id.button2, View.VISIBLE);
localAppWidgetManager.updateAppWidget(componentName, remoteViews);
} else {
clickOn = true;
camera.stopPreview();
camera.release();
camera = null;
remoteViews.setViewVisibility(R.id.button1, View.VISIBLE);
remoteViews.setViewVisibility(R.id.button2, View.GONE);
localAppWidgetManager.updateAppWidget(componentName, remoteViews);
}
} catch(Exception e) {
Log.e("Error", ""+e);
}
This problem may arise in android 6.0 if you didn't enable camera permission for your app. As from Android 6.0 you can handle the app permission weather you will give or not specific permission for an application.
So, you need to enable permission from settings->apps->your_app->enable camera permission if its not already enabled.
If your os version is 6.0 or later version try this, hope this will help.
public class RequestUserPermission {
private Activity activity;
// Storage Permissions
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.CAMERA
};
public RequestUserPermission(Activity activity) {
this.activity = activity;
}
public void verifyStoragePermissions() {
// Check if we have write permission
int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
// We don't have permission so prompt the user
ActivityCompat.requestPermissions(
activity,
PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE
);
}
}
}
**//CALL FROM YOUR ACTIVITY**
RequestUserPermission requestUserPermission = new RequestUserPermission(this);
requestUserPermission.verifyStoragePermissions();
if you try to open the camera using a cameraID that does not exist, you will receive that same error (java.lang.RuntimeException: Fail to Connect to camera service)
look at your code at this block
camera.setParameters(parameters);
camera.stopPreview();
camera.release();
camera = null;
Call release() to release the camera for use by other applications. Applications should release the camera immediately in onPause() (and re-open() it in onResume().
In above code imediately after release you are putting null to camera
Hi i hope you are dealing with a torch kind of app or something related to flash and there were many discussions went on this before and here are some useful links and tutorials to achieve your need, please go through them hope they may help you
How to turn on camera flash light programmatically in Android?
http://www.androidhive.info/2013/04/android-developing-flashlight-application/
http://www.compiletimeerror.com/2013/08/how-to-turn-onoff-camera-led-flashlight.html#.U4WH5Xbc3o4
http://android.programmerguru.com/android-flashlight-example/
You need to stopPreview() and release() once you came back from camera,
so that other application can able to access it. Make the "Camera" class as static and refer it as null in onPause(). This resolves my Issue.
Try it out:
public class CameraPhotoCapture extends Activity{
static Camera mcamera = null;
#Override
protected void onPause() {
// TODO Auto-generated method stub
if (mcamera != null) {
mcamera.stopPreview();
mcamera.release();
mcamera = null;
Log.d(DEBUG_TAG, "releaseCamera -- done");
}
super.onPause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
if (mcamera != null) {
Camera.open();
Log.d(DEBUG_TAG, "openCamera -- done");
}
super.onResume();
}
}
The simple answer I can find to this problem is I was not asking for camera permission to the user, and that's why by default camera permission was not available to my app on Marshmallow devices. I simply added permission check for the camera before starting the camera and everything works fine.
private boolean checkPermission() {
if (ContextCompat.checkSelfPermission(getApplicationContext(),
android.Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
return true;
}
return false;
}
Check the camera permission at runtime, and request the permission if it has not be granted. It works for me.
if (checkPermission()) {
initCamera();
} else {
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION);
}
Try to use this line, when you're exiting the app :
System.exit(0);
I just got a code of an Flashlight app from somewhere. It was using System.exit(0) to close the app. I removed it, knowing that this is not a good practice. Then I started to receive these errors. I tried the solution of the accepted answer, but then I started receiving some other errors. So, instead of solving them I just put this System.exit(0) line back. And, it started working fine. I know this is not a good way, but for a small flashlight app, you can try this quick solution.
Set the Required permission in Mainfest file.
Ask the Permission to accept the Camera.
It will work for me
If all your code is ok, you should check are there any other application using your camera. Then you should close other application that currently using your camera.
In my android peoject has the same issue. This is my Logcat error
03-29 19:26:04.194 224-608/? V/EmulatedCamera_BaseCamera:
getCameraInfo 03-29 19:26:04.196 224-224/? I/CameraService:
CameraService::connect call (PID -1 "com.proitzen.staffapp", camera ID
1) for HAL version default and Camera API version 1 03-29 19:26:04.196
224-224/? W/ServiceManager: Permission failure:
android.permission.CAMERA from uid=10067 pid=1776 03-29 19:26:04.196
224-224/? E/CameraService: Permission Denial: can't use the camera
pid=1776, uid=10067 03-29 19:26:04.196 1776-1776/com.proitzen.staffapp
W/CameraBase: An error occurred while connecting to camera 1: Service
not available 03-29 19:26:04.200 1776-1776/com.proitzen.staffapp
D/AndroidRuntime: Shutting down VM
No any above solutions worked for me. My android app worked in physical android devices and gave the above error only in Genymotion.
Solution : start your Genumotion emulator
Settings --> Apps ---> choose your App --> Permissions --> enable camera and Mic and storage.

Accessing front camera of mobile using flash?

Recently I went thru the code for accessing the camera using flash ActionScript3 and I have tested the code in iMac machine, iPhone and Android.Now based on this, I am developing an application for Android which includes the accessibility of the front camera. Now my Problem is I dont know how to access the front camera? We should use some other code or should we specify which camera should be accessed? First of all, can we access the front camera thru flash?
I made a simple android app. Here is the code for selecting camera window
public class SelectCameraAlertAndroid extends StartAlertAndroid_design{
public function SelectCameraAlertAndroid() {
frontCameraButton.addEventListener(MouseEvent.CLICK, onFrontCamera);
backCameraButton.addEventListener(MouseEvent.CLICK, onBackCamera);
}
private function onFrontCamera(event:MouseEvent):void {
Model.model.camera = Camera.getCamera("1");
Model.model.cameraSelectedSignal.dispatch();
dispatchEvent(new Event("closeMe"));
}
private function onBackCamera(event:MouseEvent):void {
Model.model.camera = Camera.getCamera("0");
Model.model.cameraSelectedSignal.dispatch();
dispatchEvent(new Event("closeMe"));
}
}
Not true. You can access the front camera on Android.
The only problem is that you don't get to use the CameraUI(pretty sure).
var camera = Camera.getCamera("1");
camera.setMode(stage.stageWidth, stage.stageHeight, 30, true);
var video:Video = new Video(stage.stageWidth, stage.stageHeight);
video.attachCamera(camera);
addChild(video);
Note: This answer is outdated. Please refer to the other answers for updated information.
Currently, AIR only supports access to the primary camera on an Android device.
http://forums.adobe.com/thread/849983
Official documentation: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/media/Camera.html#getCamera()
"On Android devices, you can only access the rear-facing camera."

How to detect android front camera programmatically

Can anyone tell me how to check if the android phone has a front camera too? I'd tried to use some help form https://docs.google.com/View?id=dhtsnvs6_57d2hpqtgr but Camera camera = FrontFacingCamera.getFrontFacingCamera(); sometimes works sometimes not.
Any help please?
Can anyone tell me how to check if the android phone has a front camera too?
There is no API for this, at least through Android 2.2. Sorry!
I'd tried to use some help form https://docs.google.com/View?id=dhtsnvs6_57d2hpqtgr but Camera camera = FrontFacingCamera.getFrontFacingCamera(); sometimes works sometimes not.
That is for two specific models of phones, not for Android devices in general. With luck, the upcoming Gingerbread release will add built-in support for front-facing cameras.
In the meantime, you need to get the instructions (like the one you linked to) from each and every device manufacturer and attempt to follow them.
private boolean hasFlash() {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
try {
if(camManager==null)
camManager=(CameraManager)getSystemService( CAMERA_SERVICE );
String cameraId = camManager.getCameraIdList()[1];
CameraCharacteristics cameraCharacteristics = camManager.getCameraCharacteristics( cameraId );
return cameraCharacteristics.get( CameraCharacteristics.FLASH_INFO_AVAILABLE );
} catch (Exception e) {
e.printStackTrace();
}
}
return false;
}

Categories

Resources