作为开发人员对 Android 上的文件和媒体权限的担忧

Concerns about the FILES AND MEDIA PERMISSIONS on Android as a developer

我正在开发一个将数据保存到数据库中的应用程序,我正在尝试备份和恢复我能够做到的数据库,我的问题是 API30+ 上的“不祥”许可弹出窗口

Allow management of all files

Allow this app to access modify and delete files on your device.....

Allow this app to access, modify and delete files on the device or any connected storage devices? this app may access files without asking you.

我不想做任何这些事情,我只是想获得做 backup/restore 事情的许可

这是我请求权限的代码:

    private void requestStoragePermissionExport(){
        if( (Build.VERSION.SDK_INT  >= 30 )){
            try {
                Intent intent = new Intent(Manifest.permission.MANAGE_EXTERNAL_STORAGE);
                intent.addCategory("android.intent.category.DEFAULT");
                intent.setData(Uri.parse(String.format("package:%s",getApplicationContext().getPackageName())));
                startActivityForResult(intent, 2296);
            } catch (Exception e) {
                Intent intent = new Intent();
                intent.setAction(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
                startActivityForResult(intent, 2296);
            }
        }else{
            ActivityCompat.requestPermissions(this, new String[]{
                    Manifest.permission.WRITE_EXTERNAL_STORAGE}, BACKUP_CODE);
        }
    }

有没有更好的方法来处理这个问题?

Google 限制使用广泛的文件权限,例如 MANAGE_EXTERNAL_STORAGE。您可以使用存储访问框架来获得对某些文件或目录的有限访问权限。

// Request code for selecting a PDF document.
const val PICK_PDF_FILE = 2

fun openFile(pickerInitialUri: Uri) {
    val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
        addCategory(Intent.CATEGORY_OPENABLE)
        type = "application/pdf"

        // Optionally, specify a URI for the file that should appear in the
        // system file picker when it loads.
        putExtra(DocumentsContract.EXTRA_INITIAL_URI, pickerInitialUri)
    }

    startActivityForResult(intent, PICK_PDF_FILE)
}

或者如果您想访问整个目录;

fun openDirectory(pickerInitialUri: Uri) {
    // Choose a directory using the system's file picker.
    val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE).apply {
        // Optionally, specify a URI for the directory that should be opened in
        // the system file picker when it loads.
        putExtra(DocumentsContract.EXTRA_INITIAL_URI, pickerInitialUri)
    }

    startActivityForResult(intent, your-request-code)
}

您可以访问的路径有一些限制。你可以在这里读更多关于它的内容 https://developer.android.com/training/data-storage/shared/documents-files

您可以将您的 db 文件备份到 public Documents 目录。

不需要您提到的权限。

好吧,经过一段时间的 我发现最适合自己的解决方案如下:

Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS) + File.separator + "foldername"

这不需要权限,适用于 API 30

以下和以上