62

I'm trying to access the camera on my phone. I'm writing a simple stub app prior to putting the code in a widget. I'm not getting very far. The code always throws a runtime exception "failed to connect to camera service" The code(pinched from a commonsware example) which goes wrong is:

    @Override
    public void onResume() {
        super.onResume();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
            Camera.CameraInfo info = new Camera.CameraInfo();
            for (int i = 0; i < Camera.getNumberOfCameras(); i++) {
                Camera.getCameraInfo(i, info);
                if (info.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
                    try {
                        // Gets to here OK
                        camera = Camera.open(i);
                    } catch (Exception e) {
                        e.printStackTrace();
                        //  throws runtime exception :"Failed to connect to camera service"
                    }
                }
            }
        }
}

and my manifest is (corrected 20th Oct):

 <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.nbt.cameratest"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk android:minSdkVersion="9" />
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name=".CameraTestActivity" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

            <uses-permission android:name="android.permission.CAMERA" />
            <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    </application>
</manifest>

Can anyone please suggest what might be wrong?

UPDATE 20th Oct

Logcat in SDK 4.0 is broken and wont show the end of the log, so I've cut this bit as best as I can from command line adb logcat:

W/ServiceManager( 2588): Permission failure: android.permission.CAMERA from uid=10136 pid=5744
E/CameraService( 2588): Permission Denial: can't use the camera pid=5744, uid=10136
W/System.err( 5744): java.lang.RuntimeException: Fail to connect to camera service
W/System.err( 5744):    at android.hardware.Camera.native_setup(Native Method)
W/System.err( 5744):    at android.hardware.Camera.<init>(Camera.java:294)
W/System.err( 5744):    at android.hardware.Camera.open(Camera.java:255)
etc..

I don't know why I haven't permission as it is declared in the manifest

NickT
  • 23,844
  • 11
  • 78
  • 121
  • can you give us the Logcat output with the exception? – Kurtis Nusbaum Oct 19 '11 at 23:36
  • Nothing to see now as the exception is shown as 'null' now in the catch block!? It was as described in the the question title. The logcat just shows an NPE. – NickT Oct 19 '11 at 23:59
  • so the exception is thrown exactly where you call Camera.Open()? – Kurtis Nusbaum Oct 20 '11 at 00:07
  • Yes, camera is null of course and so is 'e' in the catch block. It used to be as described i.e. 'Failed to connect..'. It knows I've got a front and a back camera (goes round the for twice). I'm calling it a day now as it's past 1.00 a.m. maybe it will become clear tomorrow. – NickT Oct 20 '11 at 00:12
  • 1
    I ended up just restarting the device and everything worked after that. – jwBurnside Jul 19 '13 at 19:32
  • see also http://stackoverflow.com/q/33030933/168034 – phunehehe Jul 08 '16 at 11:27

9 Answers9

57

Few things:

  1. Why are your use-permissions and use-features tags in your activity tag. Generally, permissions are included as direct children of your <manifest> tag. This could be part of the problem.

  2. According to the android camera open documentation, a runtime exception is thrown:

    if connection to the camera service fails (for example, if the camera is in use by another process or device policy manager has disabled the camera)

    Have you tried checking if the camera is being used by something else or if your policy manager has some setting where the camera is turned off?

  3. Don't forget the <uses-feature android:name="android.hardware.camera.autofocus" /> for autofocus.

While I'm not sure if any of these will directly help you, I think they're worth investigating if for no other reason than to simply rule out. Due diligence if you will.

EDIT As mentioned in the comments below, the solution was to move the uses-permissions up to above the application tag.

Kurtis Nusbaum
  • 30,445
  • 13
  • 78
  • 102
  • You were correct about the manifest, my mistake in cutting and pasting. It doesn't make any difference though ( see my edit). It looks like latest SDK's logcat in Eclipse is broken, so I used the command line - it is a permission error but no other process is using it as far as I can tell. – NickT Oct 20 '11 at 08:01
  • 7
    Solved it! Moved the uses-permissions up to above the application tag. I've always put them at the bottom of the manifest before and they worked OK for stuff like LOCATIONS and INTERNET. Very odd. – NickT Oct 20 '11 at 09:37
  • So the problem was with the permissions like I said? – Kurtis Nusbaum Oct 20 '11 at 13:26
  • 1
    I had the permissions as children of the manifest tack but BELOW the activity tag, which has been OK for all the other apps I've written. It seems the camera wants them ABOVE the activity tag. Thanks for your help. – NickT Oct 20 '11 at 14:58
  • Thanks guys, I run into exactly the same problem, follow the answer and add the permission below activity, doesn't work, follow the comments and add the permission before activity, works! – Baiyan Huang Jan 06 '13 at 06:27
  • 3
    Use : camera.release(); – Chetan Gaikwad Aug 09 '15 at 11:35
  • 1
    Also, If you are above Sdk.Lollipop, remember to request for permission to use camera. – nilsmagnus Apr 15 '16 at 13:08
49

For newer 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.

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
sam
  • 4,357
  • 5
  • 29
  • 34
  • 3
    Thanks sam. This was actually my problem. Really annoying that in Android 6.0 doesn't give the required permissions while developing. – vrunoa Nov 19 '15 at 23:45
  • 1
    This was an appreciated additional response. I didn't know of this issue as of yet until my Nexus 5 got the update and I started to see this pop-up after an accidental denial of the service. This also means that users should go back to older applications and handle these RuntimeException errors on older applications that support required features. – Jay Snayder Feb 25 '16 at 15:00
  • Could you post some code or link to solution, I'm not familiar yet with Marshmallow permission. – Anthony Mar 23 '16 at 15:38
  • 1
    If you mean requesting the permission from your app, take a look at the official docs here: http://developer.android.com/training/permissions/requesting.html As for the above solution it's just a manual grant for your app permissions from the app settings: Settings -> Apps -> [Your App] -> Permissions – sam Mar 24 '16 at 14:52
25

Make sure to call the release() method to release the camera when it is no longer needed, or you will not be able to use the camera. Perhaps as a sanity check, see if your regular camera works. If it says it fails, then your previous attempts at runni

Ginzorf
  • 769
  • 11
  • 19
12

The problem is related to permission. Copy following code into onCreate() method. The issue will get solved.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
        requestPermissions(new String[] {Manifest.permission.CAMERA}, 1);
    }
}

After that wait for the user action and handle his decision.

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case CAMERA_PERMISSION_REQUEST_CODE:
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //Start your camera handling here
            } else {
                AppUtils.showUserMessage("You declined to allow the app to access your camera", this);
            }
    }
}
Simon K. Gerges
  • 3,097
  • 36
  • 34
Rohit Deshmukh
  • 168
  • 1
  • 11
8

I know this question has been answered long time ago, but I would like to add a small thing.

To everyone having the same error, make sure to add this permission in you manifest file:

<uses-permission android:name="android.permission.CAMERA" />

IMPORTANT to use the CAPITAL letters for CAMERA, as I had the permission with small letters and it didn't work.

Apostrofix
  • 2,140
  • 8
  • 44
  • 71
  • And I would like to have another thing. For xamarin users, the equivalent is int the properties tab of the droid project in the required permissions list – eka808 Jan 16 '17 at 07:50
2

running your code hundred times may affect the camera to function wrongly.Your activity may be performing correctly but system could not buy it.so camera forces stop. One main tip all missed is rebooting your phone and not only eclipse..It worked for me..

minesh..
  • 155
  • 12
  • 3
    If you have issues like these you really need to look into releasing camera and other resources properly. In the end users should be able to restart your app as much as they like without having to reboot their devices. Not to mention they probably have other camera apps in use. – hcpl Apr 15 '14 at 13:53
1

since this question was asked 4 years back..and i didn't realised that unless mentioned by the Questioner..when there were no Run time permissions support.

but hoping it useful for the users who still caught in this situation.. Have a look at Run Time Permissions ,for me it solved the problem when i added Run time permissions to grant camera access. Alternatively you can grant permissions to the app manually by going to your mobile settings=>Apps=>(select your app)=>Permissions section in the appeared window and enable/disable desired permissions. hope this will work.

Muahmmad Tayyib
  • 689
  • 11
  • 28
  • Run time permissions were introduced with Android 6 which was released 4 years after I asked the question. – NickT Mar 12 '18 at 11:14
  • 1
    so whats the point . Any one facing same issue now could come there .. and fetch the solution if he isn't al ready aware of.. Dear one who is looking for solution just scrolls down to the answers ..without bothering to know when it was asked..unless it is mentioned in question....NO OFFENSE :) – Muahmmad Tayyib Mar 12 '18 at 13:32
  • @NickT i've edited my answer.. if you think that it is better answered then kindly revert the down vote :) – Muahmmad Tayyib Mar 12 '18 at 13:51
1

I came up with the same problem and I'm sharing how I fixed it. It may help some people.

First, check your Android version. If it is running on Android 6.0 and higher (API level 23+), then you need to :

  1. Declare a permission in the app manifest. Make sure to insert the permission above the application tag.

**<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />**

<application ...>
    ...
</application>

  1. Then, request that the user approve each permission at runtime

      if (ContextCompat.checkSelfPermission(thisActivity, Manifest.permission.CAMERA)
        != PackageManager.PERMISSION_GRANTED) {
    // here, Permission is not granted
    ActivityCompat.requestPermissions(this, new String[] {android.Manifest.permission.CAMERA}, 50);
    }
    

For more information, have a look at the API documentation here

Jitesh Prajapati
  • 2,533
  • 4
  • 29
  • 51
Moctar Haiz
  • 179
  • 1
  • 6
-1

when you use camera.open; and you finish using the camera write this commend camera.release(); this will stop the camera so you can use it again