Android出现FileUriExposedException,配置FileProvider仍崩溃求助
解决FileUriExposedException问题
你已经配置了FileProvider,但代码中仍在使用Uri.fromFile(file)生成file://格式的Uri,这在Android 7.0(API 24)及以上版本会触发FileUriExposedException——系统禁止直接暴露文件路径给其他应用。
修正后的openDownloadedFile函数:
fun openDownloadedFile(context: Context?, fileName: String) { val storageDirectory = Environment.getExternalStorageDirectory().toString() + STORAGE_DIRECTORY + "/${fileName}" val file = File(storageDirectory) if (file.exists() && context != null) { // 用FileProvider生成Content Uri替代file:// Uri val downloadedFileUri = FileProvider.getUriForFile( context, "net.mytvplus.stbstore.file_provider", // 与manifest中声明的authorities完全一致 file ) val fileIntent = Intent(Intent.ACTION_VIEW) fileIntent.setDataAndType(downloadedFileUri, "application/vnd.android.package-archive") // 授予目标应用临时读取权限 fileIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) fileIntent.flags = fileIntent.flags or Intent.FLAG_ACTIVITY_NEW_TASK context.startActivity(fileIntent) } }
关键修改说明:
- 替换
Uri.fromFile(file)为FileProvider.getUriForFile(),传入Context、manifest配置的authorities和目标文件 - 添加
Intent.FLAG_GRANT_READ_URI_PERMISSION,允许其他应用临时访问该文件 - 补充
context != null判空,避免空指针异常
你的file_provider.xml配置已经覆盖了整个外部存储,路径范围是合法的,无需修改。
内容的提问来源于stack exchange,提问作者Roony
相关产品推荐
相关产品推荐

