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.
Related
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
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'm trying to use the new Android camera2 api. I started with source from this tutorial : http://jylee-world.blogspot.com/2014/12/a-tutorial-of-androidhardwarecamera2.html . When I try to usb-debug-deploy it to any phone, I get a SecurityException from CameraManager.openCamera(...).
My AndroidManifest looks like this:
<uses-feature android:name="com.android.hardware.camera2.full"/>
<uses-permission android:name="android.permission.CAMERA"/>
This seems to be what every tutorial I've been able to find does. I'm able to get permission for other actions; for example, I can make the camera vibrate just fine. I'm also able to enumerate cameras with CameraManager.getCameraIdLists() just fine, but I'm not sure if that actually requires permission. But I can't openCamera.
Are there some additional permissions I need? Am I doing something wrong?
Thanks for the help!
This is my full stack trace:
SecurityException
java.lang.SecurityException: Lacking privileges to access camera serviceat android.hardware.camera2.utils.CameraBinderDecorator.throwOnError(CameraBinderDecorator.java:108)
at android.hardware.camera2.legacy.CameraDeviceUserShim.connectBinderShim(CameraDeviceUserShim.java:336)
at android.hardware.camera2.CameraManager.openCameraDeviceUserAsync(CameraManager.java:327)
at android.hardware.camera2.CameraManager.openCamera(CameraManager.java:457)
at com.example.quinnfreedman.camera2test.MainActivity$1.onSurfaceTextureAvailable(MainActivity.java:74)
at android.view.TextureView.getHardwareLayer(TextureView.java:368)
at android.view.View.updateDisplayListIfDirty(View.java:15167)
at android.view.View.draw(View.java:15964)
at android.view.ViewGroup.drawChild(ViewGroup.java:3612)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3402)
at android.view.View.updateDisplayListIfDirty(View.java:15185)
at android.view.View.draw(View.java:15964)
at android.view.ViewGroup.drawChild(ViewGroup.java:3612)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3402)
at android.view.View.updateDisplayListIfDirty(View.java:15185)
at android.view.View.draw(View.java:15964)
at android.view.ViewGroup.drawChild(ViewGroup.java:3612)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3402)
at android.view.View.updateDisplayListIfDirty(View.java:15185)
at android.view.View.draw(View.java:15964)
at android.view.ViewGroup.drawChild(ViewGroup.java:3612)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3402)
at android.view.View.draw(View.java:16197)
at com.android.internal.policy.PhoneWindow$DecorView.draw(PhoneWindow.java:2690)
at android.view.View.updateDisplayListIfDirty(View.java:15190)
at android.view.ThreadedRenderer.updateViewTreeDisplayList(ThreadedRenderer.java:281)
at android.view.ThreadedRenderer.updateRootDisplayList(ThreadedRenderer.java:287)
at android.view.ThreadedRenderer.draw(ThreadedRenderer.java:322)
at android.view.ViewRootImpl.draw(ViewRootImpl.java:2627)
at android.view.ViewRootImpl.performDraw(ViewRootImpl.java:2446)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2079)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1119)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6060)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
at android.view.Choreographer.doCallbacks(Choreographer.java:670)
at android.view.Choreographer.doFrame(Choreographer.java:606)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
at android.os.Handler.handleCallback(Handler.java:746)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
In Android M, run time permission check is required for dangerous permission. You can see dangerous permission here.
Check for permission :
// Assume thisActivity is the current activity
int permissionCheck = ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.CAMERA);
If the app has the permission, the method returns PackageManager.PERMISSION_GRANTED, and the app can proceed with the operation. If the app does not have the permission, the method returns PERMISSION_DENIED, and the app has to explicitly ask the user for permission.
For details: https://developer.android.com/training/permissions/requesting.html#perm-request
Just close your camera device in onSurfaceTextureDestroyed function
onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture){cameraDevice.close();cameraDevice = null;}
Security exception will get fix
When you are running your application on android 6+, you need to give the famous runtime permissions.
https://developer.android.com/training/permissions/requesting.html
The permission you are trying to give is considered a dangerous permissions android.
https://developer.android.com/guide/topics/security/permissions.html#normal-dangerous
Different of other responses about runtime permission, I suggest you to use this https://github.com/Karumi/Dexter
This lib makes the permission handling easily
Struggled with this off and on for weeks, thinking several times I'd solved the problem. In the end, none of the "fixes" I'd read about here worked. Then, after putting in ~100 Log.v statements in my Java, I realized it was a threading issue that might, or might not, kick off this error depending on events on the camera. Basically, I think, the main program was running on the main thread, but there was an extra thread kicked off by the following statement:
//this code seems to be the culprit ... commenting it out solve my problem
private void showToast(final String text) {
final Activity activity = MyStupidProgram.this;
if (activity != null) {
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(activity, text, Toast.LENGTH_SHORT).show();
}
});
}
}
So while there's nothing in this statement calling the camera, perhaps because of thread safety, Android 5.x and 6.x were throwing security errors when I called showToast('some crap');
Commenting that out and just using a Toast.makeText('blah blah'); statement, I was able to get rid of the security error.
Additionally, I added this to the code on the page's onCreate(); statement, to catch any issues on the main thread:
Thread.setDefaultUncaughtExceptionHandler(
new Thread.UncaughtExceptionHandler() {
#Override
public void uncaughtException(
Thread paramThread,
Throwable paramThrowable
) {
//Do your own error handling here
if (exceptionHandler != null)
exceptionHandler.uncaughtException(
paramThread,
paramThrowable
); //Delegates to Android's error handling
else
System.exit(2); //Prevents the service/app from freezing
}
});
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.
I have an android system service(not app) which is used by android applications. I want to add a customed permission to this system service, then an application has to have this permission to access my service.
Now, I've added a permision in /frameworks/base/core/res/AndroidManifest.xml, say com.test.testpermission.
But what else should I do to use this permission in the system service?
Inside the service code you need to add permission check into all public API's exposed by the service. To check the permissions you can use this approach:
private boolean checkPermission() {
if (getContext().checkCallingOrSelfPermission("com.test.testpermission") == PackageManager.PERMISSION_GRANTED) {
return true;
}
return false;
}
So, the client app have to have your permission listed in its manifest.
I never tried it by myself but I can see it is used by TelephonyRegistry service for example.
For native code I can see this in camera service:
if (!checkCallingPermission(
String16("android.permission.CAMERA"))) {
const int uid = getCallingUid();
LOGE("Permission Denial: "
"can't use the camera pid=%d, uid=%d", pid, uid);
return PERMISSION_DENIED;
}