[英]Concerns about the FILES AND MEDIA PERMISSIONS on Android as a developer
我正在开发一个将数据保存到数据库中的应用程序,我正在尝试备份和恢复我能够执行的数据库,我的问题是 API30+ 上的“不祥”权限弹出窗口
允许此应用访问、修改和删除设备或任何连接的存储设备上的文件吗? 这个应用程序可能会在不询问您的情况下访问文件。
我不想做任何这些事情,我只是想要允许做备份/恢复的事情
这是我请求许可的代码:
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 文件备份到公共 Documents 目录即可。
不需要你提到的权限。
好吧,经过一番研究,我发现最适合自己的解决方案如下:
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS) + File.separator + "foldername"
这不需要权限,可以在 API 30 的下方和上方工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.