Andrew Torr Andrew Torr - 1 year ago 177
Java Question

Android runtime permissions- how to implement

Android Developer Documentation gives this example of requesting permissions at runtime:

// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(thisActivity,
!= PackageManager.PERMISSION_GRANTED) {

// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
Manifest.permission.READ_CONTACTS)) {

// Show an expanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.

} else {

// No explanation needed, we can request the permission.

new String[]{Manifest.permission.READ_CONTACTS},

// app-defined int constant. The callback method gets the
// result of the request.

What is "MY_PERMISSIONS_REQUEST_READ_CONTACTS" in this example? It says it's an app-defined int constant, but does that mean I should make a and declare a public static int? What should the value be?

In other examples I see people use 1 here, or 0 or 0xFFEEDDCC, but I can't find an explanation of what it is. Can someone explain to me what needs to go here and why? (In my case, I need to make sure the app has permission to access fine location)

The ActivityCompat documentation says "Application specific request code to match with a result reported to onRequestPermissionsResult"? This does not help me.

Answer Source


It is an int, to tie a particular requestPermissions() call to the corresponding onRequestPermissionsResult() callback.

Under the covers, requestPermissions() uses startActivityForResult(); this int serves the same role as it does in startActivityForResult().

does that mean I should make a and declare a public static int?

I would just make it a private static final int in the activity. But, you can declare it wherever you want.

What should the value be?

I seem to recall that it needs to be below 0x8000000, but otherwise it can be whatever you want. The value that you use for each requestPermissions() call in an activity should get a distinct int, but the actual numbers do not matter.

If your activity has only one requestPermissions() call, then the int value really does not matter. But many apps will have several requestPermissions() calls in an activity. In that case, the developer may need to know, in onRequestPermissionsResult(), what request this is the result for.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download