Skip to content

Instantly share code, notes, and snippets.

@achinverma
Created September 20, 2018 04:57
Show Gist options
  • Save achinverma/bc6e78c3ff91e3dd1fa336e285927f4f to your computer and use it in GitHub Desktop.
Save achinverma/bc6e78c3ff91e3dd1fa336e285927f4f to your computer and use it in GitHub Desktop.
Android Permissions
// called in a standard activity, use ContextCompat.checkSelfPermission for AppCompActivity
int permissionCheck = checkSelfPermission(this, Manifest.permission.WRITE_CALENDAR);
if (!permissionCheck == PackageManager.PERMISSION_GRANTED) {
// User may have declined earlier, ask Android if we should show him a reason
if (shouldShowRequestPermissionRationale(thisActivity, Manifest.permission.WRITE_CALENDAR)) {
// show an explanation to the user
// Good practise: don't block thread after the user sees the explanation, try again to request the permission.
} else {
// request the permission.
// CALLBACK_NUMBER is a integer constants
requestPermissions(thisActivity, new String[]{Manifest.permission.WRITE_CALENDAR}, CALLBACK_NUMBER);
// The callback method gets the result of the request.
}
} else {
// got permission use it
}
//If the user is asked to grant the permission, you receive a call back.
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_CONTACTS: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, do your work....
} else {
// permission denied
// Disable the functionality that depends on this permission.
}
return;
}
// other 'case' statements for other permssions
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment