user2966445 user2966445 - 4 months ago 13
Java Question

Android Studio 2 - Camera SecurityException

I'm trying to use camera intent to capture a photo and display in an ImageView.

Any time the camera intent is started, the following exception occurs:

java.lang.SecurityException: Permission Denial: starting Intent { act=android.media.action.IMAGE_CAPTURE cmp=com.android.camera/.Camera } from ProcessRecord{c4afeea 3037:com.example.jt.testapp/u0a57} (pid=3037, uid=10057) with revoked permission android.permission.CAMERA


Calling code:

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Button gallery = (Button) findViewById(R.id.btnGallery);
gallery.setOnClickListener(new Gallery(this));

Button camera = (Button) findViewById(R.id.btnCamera);
camera.setOnClickListener(new Camera(this));

}


What is the correct manifest permission to avoid receiving the above exception?

Answer

You are using the right permission: android.permission.CAMERA

When you want access to the Camera permission you have to ask it at runtime when running on Marshmallow.

First check whether the permission is granted and when that isn't the case then request the permission:

if (ContextCompat.checkSelfPermission(thisActivity, Manifest.permission.CAMERA)
    != PackageManager.PERMISSION_GRANTED) {
  ActivityCompat.requestPermissions(thisActivity,
            new String[]{Manifest.permission.CAMERA},
            0);
}

This is explained here in detail in the documentation: http://developer.android.com/training/permissions/requesting.html