Android 6.0 Getting Dynamic Permissions Code Sample

  • 2021-12-11 08:43:47
  • OfStack

The Android system groups all dangerous permissions, called permission groups. Risk permissions belonging to the same group are automatically consolidated and granted, and if a user grants permission to apply a permission group, the application gets all permissions under that permission group (provided the permissions are declared in AndroidManifest. xml).

The list of dangerous permissions and permission groups is as follows: Permission groups corresponding to dangerous permissions declared in AndroidManifest. xml can be "set" in the system- > "Application"- > "Application information"- > "Permissions", you can manually authorize and cancel authorization.

1. If the device system is Android 6.0 (API 23) or later, and the applied targetSdkVersion is 23 or later, the user authorization needs to be dynamically requested at runtime for the dangerous rights declared in AndroidManifest. xml.

2. API of dynamic permission request related operations is encapsulated in android. support. v4 package, and Activity that initiates permission request needs to directly or indirectly inherit android. support. v4.app. FragmentActivity.

3. You can also initiate permission requests in Fragment that directly or indirectly inherits android. support. v4.app. Fragment.

First register in the manifest file

Then encapsulate the permissions into an String array in MainActivity. java


static final String[] PERMISSION = new String[]{
      Manifest.permission.READ_PHONE_STATE,
      Manifest.permission.WRITE_EXTERNAL_STORAGE,
      Manifest.permission.RECORD_AUDIO,
      Manifest.permission.RECEIVE_BOOT_COMPLETED
  };

Then add 1 code to the onCreate () method:


if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
      //Android 6.0 Apply for authority 
      ActivityCompat.requestPermissions(this, PERMISSION, 1);
    } else {
      Toast.makeText(this, " Success ", Toast.LENGTH_SHORT).show();
    }

I usually write the above code in another method and then call it in the onCreate () method.


Related articles: