使用以下代码段,我们在Android 10中的getExternalFilesDir()下的子文件夹中创建了一个文件。但是,在创建之后,如果我们尝试采用persistableUriPermission,则会引发异常“不存在此类许可....”。我们需要进行检查,以了解该文件以后是否可以在通用实用程序中读取,否则我们必须进行复制。请让我们知道我们可能在做错什么以及如何解决此问题。感谢您的帮助。
ParcelFileDescriptor filePFD =
cxt.getContentResolver().openFileDescriptor(Uri.parse(pathFileToSend), "r");
FileDescriptor fd = filePFD.getFileDescriptor();
FileInputStream fIn = new FileInputStream(fd);
File fileBaseFolder = new File(Utils.GetRootDirectory().getAbsolutePath(), Utils.DESTINATION);
if (!fileBaseFolder.exists())
fileBaseFolder.mkdirs();
if (fileBaseFolder.exists()) {
File copyFile = new File(fileBaseFolder.getAbsolutePath(), nameOfFile);
FileOutputStream fOut = new FileOutputStream(copyFile);
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = fIn.read(data)) != -1) {
total += count;
fOut.write(data, 0, count);
}
fOut.close();
Uri copiedFileUri =
FileProvider.getUriForFile(cxt,
cxt.getString(R.string.file_provider_authority),
copyFile);
if (null != copiedFileUri)
{
try {
/*At this line, an exception is thrown - No persistable permissions exist.. */
cxt.getContentResolver().takePersistableUriPermission(copiedFileUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
} catch (Exception e) {
e.printStackTrace();
}
}
takePersistableUriPermission()
代表您从Storage Access Framework获得的Uri
值(例如ACTION_OPEN_DOCUMENT
)。它不适用于FileProvider
。并且,您不需要权限即可在Android 4.4及更高版本上使用getExternalFilesDir()
。