[英]Android SD Card Write Permission using SAF (Storage Access Framework)
After a lot of findings about how to write(and rename) a file in SD Card (android 5 and above), I think the new SAF provided by android will be required to take permission from user to write SD card file. 关于如何在SD卡(android 5及以上版本)中编写(和重命名)文件的大量调查结果后,我认为android提供的新SAF需要获得用户写入SD卡文件的许可。
I have seen in this File Manger Application ES File Explorer that initially it takes read and write permission the following way as shown in pictures. 我在这个文件管理器应用程序ES文件资源管理器中看到,最初它采用以下方式读取和写入权限,如图片所示。
After selecting sd card, the write permission is granted. 选择SD卡后,授予写入权限。
So in the same way I tried to use SAF, but failed in renaming a file. 因此我尝试使用SAF的方式相同,但重命名文件失败了。 My code:
我的代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rename = (Button) findViewById(R.id.rename);
startActivityForResult(new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE), 42);
}
@Override
public void onActivityResult(int requestCode,int resultCode,Intent resultData) {
if (resultCode != RESULT_OK)
return;
Uri treeUri = resultData.getData();
DocumentFile pickedDir = DocumentFile.fromTreeUri(this, treeUri);
grantUriPermission(getPackageName(), treeUri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
getContentResolver().takePersistableUriPermission(treeUri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
}
public void renameclick(View v) {
File ff = new File("/storage/sdcard1/try1.jpg");
try {
ff.createNewFile();
} catch (Exception e) {
Log.d("error", "creating");
e.printStackTrace();
}
}
Still after running the code I get EAacces permission denied. 在运行代码之后,我仍然拒绝EAacces权限。
Letting the user choose the "SD card" or even the "Internal storage" SAF root give your application access to the corresponding storage, but only through the SAF API, not directly via the filesystem. 让用户选择“SD卡”甚至“内部存储”SAF根目录,使您的应用程序可以访问相应的存储,但只能通过SAF API,而不能直接通过文件系统。 For example you code could be translated into something like :
例如,您可以将代码翻译成以下内容:
public void writeFile(DocumentFile pickedDir) {
try {
DocumentFile file = pickedDir.createFile("image/jpeg", "try2.jpg");
OutputStream out = getContentResolver().openOutputStream(file.getUri());
try {
// write the image content
} finally {
out.close();
}
} catch (IOException e) {
throw new RuntimeException("Something went wrong : " + e.getMessage(), e);
}
}
In recent version of Android, accessing data outside your application using java.io.File
is almost completely deprecated. 在最新版本的Android中,使用
java.io.File
访问应用程序外部的数据几乎完全被弃用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.