Last active
November 10, 2015 13:20
-
-
Save tseglevskiy/cc715f36e10ad81c83b6 to your computer and use it in GitHub Desktop.
App Permissions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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