Skip to content

Instantly share code, notes, and snippets.

@wszdwp
Created October 10, 2018 15:08
Show Gist options
  • Select an option

  • Save wszdwp/860bede13f36c1fde207ec9b0be724ed to your computer and use it in GitHub Desktop.

Select an option

Save wszdwp/860bede13f36c1fde207ec9b0be724ed to your computer and use it in GitHub Desktop.
Request permissions at runtime in android
// check permissions
private void requestForGpsPermission() {
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_ACCESS_FINE_LOCATION);
}
}
// [Android training](https://developer.android.com/training/permissions/requesting#java)
// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.READ_CONTACTS)
!= PackageManager.PERMISSION_GRANTED) {
// Permission is not granted
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
Manifest.permission.READ_CONTACTS)) {
// Show an explanation 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; request the permission
ActivityCompat.requestPermissions(thisActivity,
new String[]{Manifest.permission.READ_CONTACTS},
MY_PERMISSIONS_REQUEST_READ_CONTACTS);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
} else {
// Permission has already been granted
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment