Skip to content

Instantly share code, notes, and snippets.

@wszdwp
Created November 1, 2018 18:46
Show Gist options
  • Select an option

  • Save wszdwp/5f333753f36d61b830a5d84d9089c2ff to your computer and use it in GitHub Desktop.

Select an option

Save wszdwp/5f333753f36d61b830a5d84d9089c2ff to your computer and use it in GitHub Desktop.
Android 6.0+ dangerous permissions runtime request
// if the device is running Android 6.0 (API level 23)
// and the app's targetSdkVersion is 23 or higher,
//the following system behavior applies when your app requests a dangerous permission:
// 1.
//If the app doesn't currently have any permissions in the permission group,
//the system shows the permission request dialog to the user describing the permission group
//that the app wants access to. The dialog doesn't describe the specific permission within
//that group. For example, if an app requests the READ_CONTACTS permission,
//the system dialog just says the app needs access to the device's contacts.
//If the user grants approval, the system gives the app just the permission it requested.
// 2.
//If the app has already been granted another dangerous permission in the same permission group,
//the system immediately grants the permission without any interaction with the user.
//For example, if an app had previously requested and been granted the READ_CONTACTS permission,
//and it then requests WRITE_CONTACTS, the system immediately grants that permission without
//showing the permissions dialog to the user.
//refs
//https://developer.android.com/guide/topics/permissions/overview#permission-groups
//https://developer.android.com/reference/android/os/Build.VERSION_CODES
public static final int REQUEST_DANGEROUS_PERMISSIONS = 1001;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestDangerousPermissions();
}
private void requestDangerousPermissions() {
List<String> perms = new ArrayList<>();
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
perms.add(Manifest.permission.ACCESS_FINE_LOCATION);
}
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
perms.add(Manifest.permission.CAMERA);
}
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
perms.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
if (perms.size() > 0) {
ActivityCompat.requestPermissions(this,
perms.toArray(new String[0]),
REQUEST_DANGEROUS_PERMISSIONS);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_DANGEROUS_PERMISSIONS) {
if (requestCode == RESULT_CANCELED) {
//finish();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment