Pajri Aprilio
Pajri Aprilio

Reputation: 322

Camera permission not automatically granted

I try to access camera using Camera.open() But it throws exception Fail to connect to camera service.

I checked camera permission in Settings->Apps->MyApp->Permission->Camera and it's not granted. I have already added camera permission in android manifest.

<uses-permission android:name="android.permission.CAMERA"/>
    <uses-feature android:name="android.hardware.camera2" android:required="true"/>

Why is it not automatically granted at the first time ? What is the best practice to handle this ?

Upvotes: 1

Views: 9221

Answers (1)

Rahat Zaman
Rahat Zaman

Reputation: 1382

First check if the user grant the permission:

if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA)
    == PackageManager.PERMISSION_DENIED)

Then, you could use this to request to the user:

ActivityCompat.requestPermissions(activity, new String[] {Manifest.permission.CAMERA}, requestCode);

And in marshmallow and later, it appears the dialog


After requesting the permission alert will display to ask permission contains allow and deny options. After clicking action we can get result of the request with the following method.

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    if (requestCode == MY_CAMERA_REQUEST_CODE) {
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

            Toast.makeText(this, "camera permission granted", Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(this, "camera permission denied", Toast.LENGTH_LONG).show();
        }
    }
}

If you don't believe me, I have taken the answer from here.

Upvotes: 2

Related Questions