gpt4 book ai didi

java - 通过 ClipData.Item.getUri 暴露在应用程序之外

转载 作者:IT老高 更新时间:2023-10-28 13:15:44 26 4
gpt4 key购买 nike

在 Android 文件系统中添加新功能后,我正在尝试解决一个问题,但我收到此错误:

android.os.FileUriExposedException: file:///storage/emulated/0/MyApp/Camera_20180105_172234.jpg exposed beyond app through ClipData.Item.getUri()

所以我希望有人能帮我解决这个问题:)

谢谢

private Uri getTempUri() {
// Create an image file name
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
String dt = sdf.format(new Date());
imageFile = null;
imageFile = new File(Environment.getExternalStorageDirectory()
+ "/MyApp/", "Camera_" + dt + ".jpg");
AppLog.Log(
TAG,
"New Camera Image Path:- "
+ Environment.getExternalStorageDirectory()
+ "/MyApp/" + "Camera_" + dt + ".jpg");
File file = new File(Environment.getExternalStorageDirectory() + "/MyApp");
if (!file.exists()) {
file.mkdir();
}
imagePath = Environment.getExternalStorageDirectory() + "/MyApp/"
+ "Camera_" + dt + ".jpg";
imageUri = Uri.fromFile(imageFile);
return imageUri;
}

最佳答案

对于 sdk 24 及更高版本,如果您需要在应用存储之外获取文件的 Uri,则会出现此错误。
@eranda.del 解决方案可让您更改策略以允许这样做,并且效果很好。

但是,如果您想遵循 google 指南而无需更改应用的 API 政策,则必须使用 FileProvider。

首先要获取文件的 URI,您需要使用 FileProvider.getUriForFile() 方法:

Uri imageUri = FileProvider.getUriForFile(
MainActivity.this,
"com.example.homefolder.example.provider", //(use your app signature + ".provider" )
imageFile);

然后你需要在你的 android manifest 中配置你的提供者:

<application>
...
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.example.homefolder.example.provider"
android:exported="false"
android:grantUriPermissions="true">
<!-- ressource file to create -->
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths">
</meta-data>
</provider>
</application>

(在“authorities”中使用与 getUriForFile() 方法的第二个参数相同的值(应用签名+“.provider”))

最后你需要创建资源文件:“file_paths”。这个文件需要在 res/xml 目录下创建(你可能也需要创建这个目录):

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="." />
</paths>

关于java - 通过 ClipData.Item.getUri 暴露在应用程序之外,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48117511/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com