Skip to content

Instantly share code, notes, and snippets.

@tseglevskiy
Last active November 10, 2015 13:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tseglevskiy/cc715f36e10ad81c83b6 to your computer and use it in GitHub Desktop.
Save tseglevskiy/cc715f36e10ad81c83b6 to your computer and use it in GitHub Desktop.
App Permissions
private void requestPermissionAndExecute(
final String permission,
final int requestCode,
final Runnable granted,
final Runnable denied
)
{
grantedActions.put(requestCode, granted);
deniedActions.put(requestCode, denied);
if (ContextCompat.checkSelfPermission(this, permission) == PackageManager
.PERMISSION_GRANTED) {
// права есть, всё хорошо
granted.run();
return;
}
// прав нет
boolean shouldShow =
ActivityCompat.shouldShowRequestPermissionRationale(this, permission);
if (!shouldShow) {
// пользователю можно ничего не объяснять
ActivityCompat.requestPermissions(this,
new String[]{permission},
requestCode
);
return;
}
// вопрос пользователю
locationPermissionDialog = new AlertDialog.Builder(this)
.setMessage("Приложению для работы необходимо " +
permission +
" Пожалуйста, разрешите доступ.")
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// если пользователь нажал ОК, то вероятно он
// действительно сходил в настройки и разрешил доступ
// значит мы может запросить доступ
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{permission},
requestCode
);
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
denied.run();
}
})
.setCancelable(false)
.create();
locationPermissionDialog.show();
}
@Override
public void onRequestPermissionsResult(int requestCode,
String[] permissions,
int[] grantResults)
{
if (grantedActions.containsKey(requestCode)) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
grantedActions.get(requestCode).run();
} else {
deniedActions.get(requestCode).run();
}
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment