【问题标题】:Dynamically replace applicationId in the file_paths.xml动态替换file_paths.xml中的applicationId
【发布时间】:2016-08-30 09:50:23
【问题描述】:

我已经使用以下res/xml/file_paths.xml 设置了一个 FileProvider:

<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="suggestions" path="Android/data/com.example.app.dev/files/suggestions" />
</paths>

问题是,我有许多改变applicationId 的产品风格。有没有办法用正确的 applicationId 替换该值,而无需为每种产品风味创建文件路径?喜欢替换像Android/data/{appId}/files/suggestions 这样的标签吗?甚至使用相对路径...(我已经尝试了所有方法,但只有这个完整路径有效)。

【问题讨论】:

    标签: android android-studio gradle


    【解决方案1】:

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

    defaultConfig {
        applicationId "com.example.myapp"
        ...
        resValue 'string', 'images_file_path', "Android/data/" + applicationId + "/files/Pictures"
    }
    

    然后您可以在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>
    

    【讨论】:

    • 如果你把 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 没有任何好处。
    • android:path 在这里不起作用。它需要包含路径属性。
    【解决方案2】:

    您根本不需要在 file_paths.xml 中使用 applicationId。只需将external_path 子句替换为:

    <external-files-path name="my_images" path="Pictures" />
    

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

    从https://stackoverflow.com/a/40563179/1033645复制的解决方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-27
      • 1970-01-01
      • 1970-01-01
      • 2020-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多