I really struggle with this since a while :( as I need an solution that works within UNITY3D.
I need to check if the user has given the permission to access the Android device camera (and location on a second level).
Normally the app start by asking for this permissions at launch, but if the user denies the access for the camera I need to know and check that later.
Otherwise the user could hit the camera UI button I made and try to access the camera via webcamtexture... and that leads into a crash of the app.
Since Android API 23 you cannot ignore or already grant permissions by changing the android manifest like I tried after reading several posts about that.
Thank's to everyone who has an idea to solve this.
Check this library: https://github.com/sanukin39/UniAndroidPermission
In that library I got these methods to check and request Permission.
public static void requestPermission(String permissionStr){
if(!hasPermission(permissionStr)) {
UnityPlayer.currentActivity.requestPermissions(new String[]{permissionStr}, 0);
}
}
public static boolean hasPermission(String permissionStr) {
if(Build.VERSION.SDK_INT < 23) {
return true;
}
Context context = UnityPlayer.currentActivity.getApplicationContext();
return context.checkCallingOrSelfPermission(permissionStr) == PackageManager.PERMISSION_GRANTED;
}
Hope it helps:)
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.
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.
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.
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;
}