Android文件读写权限

首先需要在manifest中添加静态权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>

然后在activity的Oncreate方法中,动态申请(6.0以后要求)

//先定义
private static final int REQUEST_EXTERNAL_STORAGE = 1;

private static String[] PERMISSIONS_STORAGE = { 
        "android.permission.READ_EXTERNAL_STORAGE",
        "android.permission.WRITE_EXTERNAL_STORAGE" };
        
//然后通过一个函数来申请
public static void verifyStoragePermissions(Activity activity) { 
    try { 
        //检测是否有写的权限
        int permission = ActivityCompat.checkSelfPermission(activity,
                "android.permission.WRITE_EXTERNAL_STORAGE");
        if (permission != PackageManager.PERMISSION_GRANTED) { 
        // 没有写的权限,去申请写的权限,会弹出对话框
            ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,REQUEST_EXTERNAL_STORAGE);
        }
    } catch (Exception e) { 
        e.printStackTrace();
    }
}

具体使用是在activity的Oncreate方法中

@Override
protected void onCreate(Bundle savedInstanceState){ 
    super.onCreate(savedInstanceState);
    setContextView(R.layout.activity_main);
    verifyStoragePermissions(this);
    
    ...
    
}

参考
Android 添加读写外部存储权限

    原文作者:gaussrieman123
    原文地址: https://blog.csdn.net/gaussrieman123/article/details/89488055
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞