首页 文章

通过ClipData.Item.getUri暴露在app之外

提问于
浏览
32

嗨我想在android文件系统中添加新功能后修复问题,但是我收到此错误:

android.os.FileUriExposedException:file:///storage/emulated/0/MyApp/Camera_20180105_172234.jpg通过ClipData.Item.getUri()暴露在app之外

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

谢谢

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

2 回答

  • 75

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

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

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

    (在“authority”中使用与getUriForFile()方法的第二个参数相同的值(app signature“.provider”))

    最后,您需要创建ressources文件:“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>
    

相关问题