Android 12 SD dynamically applies for read and write permissions

How to dynamically apply for read and write permissions in android 12

Android 12 not only needs to apply for read and write permissions in AndroidManifest.xml, but also needs to apply dynamically in the code. It only takes two steps to dynamically apply for read and write permissions.

  1. Apply for read and write permissions in the AndroidManifest.xml file
   <!--读写权限-->
    <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"
        tools:ignore="ScopedStorage" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  1. Dynamic application method in the code startup MainActivity
 private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private final static String[] PERMISSIONS_STORAGE = {
    
    
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,};

 public void verifyStoragePermissions(Activity activity) {
    
    

        try {
    
    
            //检测是否有写的权限
            int permission = ActivityCompat.checkSelfPermission(activity,
                    "android.permission.WRITE_EXTERNAL_STORAGE");
            if (permission != PackageManager.PERMISSION_GRANTED) {
    
    
                // 没有写的权限,去申请写的权限,会弹出对话框
                ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
            }
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }

    }

The following is the Manifest.class class about dynamic permission application. If you are interested, you can learn about it.
insert image description here

Guess you like

Origin blog.csdn.net/m0_49412847/article/details/130315585