通过 ClipData.Item.getUri 在应用之外公开

2022-08-31 08:10:43

我试图在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;
}

答案 1

对于 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清单中配置您的提供商:

<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>

(在“权限”中使用与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>

答案 2

在开始相机或文件浏览之前添加以下代码块

    StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
    StrictMode.setVmPolicy(builder.build());

请参考推荐链接严格模式及其说明的所有用法和技术细节。


推荐