我有一个应用程序,可以从文件管理器打开txt文件,编辑它们并保存对该文件的更改。
问题是,当uri方案是file://时,一切都很好。但是,如果uri方案是content://,则在尝试grantUriPermissions()时会出现异常。
下面是我如何尝试保存文件:
OutputStream os;
try {
List<ResolveInfo> resInfoList = context.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo : resInfoList) {
String packageName = resolveInfo.activityInfo.packageName;
context.grantUriPermission(packageName, uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
os = context.getContentResolver().openOutputStream(uri);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8));
writer.write(newText.trim());
writer.flush();
writer.close();
os.close();
context.revokeUriPermission(uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
} catch (IOException e) {
e.printStackTrace();
}我得到:
java.lang.SecurityException: Permission Denial: writing com.android.fileexplorer.provider.FileExplorerFileProvider uri content://com.mi.android.globalFileexplorer.myprovider/external_files/txtpad/uu.txt from pid=32456, uid=10208 requires the provider be exported, or grantUriPermission()我的<provider/> in AndroidManifest
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths" />
</provider>我在AndroidManifest中的活动标签中有这个
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="content" />
<data android:scheme="file" />
<data android:mimeType="text/*" />
</intent-filter>发布于 2018-04-29 19:54:16
首先,去掉一些代码,留给您:
OutputStream os;
try {
os = context.getContentResolver().openOutputStream(uri);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8));
writer.write(newText.trim());
writer.flush();
writer.close();
os.close();
} catch (IOException e) {
e.printStackTrace();
}我删除的代码与授予Uri标识的内容其他应用程序的权限有关。您没有对其他应用程序做任何事情,特别是revokeUriPermission()位可能会破坏您自己的应用程序对内容的访问。
然后,完全卸载和重新安装你的应用程序,看看事情是否开始工作。
如果没有,请确保:
Uri (通过getIntent().getData()),或者Uri传递给另一个组件,则将FLAG_GRANT_WRITE_URI_PERMISSION添加到用于启动该组件的Intent (可能还包括FLAG_GRANT_READ_URI_PERMISSION,取决于该其他组件需要什么)https://stackoverflow.com/questions/50090394
复制相似问题