动态替换file_paths.xml中的applicationId

Fab*_*cio 15 android gradle android-studio

我已经设置了一个FileProvider,其中包含以下内容res/xml/file_paths.xml:

<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="suggestions" path="Android/data/com.example.app.dev/files/suggestions" />
</paths>
Run Code Online (Sandbox Code Playgroud)

问题是,我有很多产品口味改变了applicationId.有没有办法用适当的applicationId替换该值而不为每个产品风格创建文件路径?就像更换这样的标签一样Android/data/{appId}/files/suggestions?甚至使用相对路径...(我已经尝试了所有东西,但只有这条完整的路径才有效).

小智 17

我设法通过使用Gradle在build.gradle文件中动态创建字符串资源值来表示文件路径来解决此问题:

defaultConfig {
    applicationId "com.example.myapp"
    ...
    resValue 'string', 'images_file_path', "Android/data/" + applicationId + "/files/Pictures"
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以在中引用此字符串资源值 res/xml/file_paths.xml

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="my_images" android:path="@string/images_file_path" />
</paths>
Run Code Online (Sandbox Code Playgroud)

  • 如果您放置“android:”命名空间,FileProvider 将不会读取“path”属性的值。如果您编写 `path="Android/data/com.example.myapp/files/Pictures"`,URI 将如下所示:content://com.example.myapp.photos_provider/my_images/my_file.jpg。这是正确的。但是,如果您编写 `android:path="Android/data/com.example.myapp/files/Pictures"` (或使用答案中的资源中的字符串),您将得到: content://com.example.myapp.photos_provider /my_images/Android/data/com.example.myapp/files/Pictures/my_file.jpg。所以使用 FileProvider 不会带来任何好处。 (2认同)

jav*_*ian 12

您根本不需要使用applicationId file_paths.xml.只需将external_path条款替换为:

<external-files-path name="my_images" path="Pictures" />
Run Code Online (Sandbox Code Playgroud)

这将需要24.0.0或更高版本的支持库.

解决方案从/sf/answers/2839422561/复制.