且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-11-16 19:25:49

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

但是,如果您想遵循Google指南而不必更改应用程序的API政策,则必须使用FileProvider.

For sdk 24 and up, if you need to get the Uri of a file outside your app storage you have this error.
@eranda.del solutions let you change the policy to allow this and it works fine.

However if you want to follow the google guideline without having to change the API policy of your app you have to use a FileProvider.

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

At first to get the URI of a file you need to use FileProvider.getUriForFile() method:

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

然后,您需要在android清单中配置您的提供程序:

Then you need to configure your provider in your 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>

(在当局"中,使用与getUriForFile()方法的第二个参数(应用程序签名+".provider")相同的值)

(In "authorities" use the same value than the second argument of the getUriForFile() method (app signature + ".provider"))

最后,您需要创建资源文件:"file_paths". 此文件需要在res/xml目录下创建(您可能也需要创建此目录):

And finally you need to create the ressources file: "file_paths". This file need to be created under the res/xml directory (you probably need to create this directory too) :

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