在 Android 应用中设置 android:authorities 属性主要是为 ContentProvider 或 FileProvider 定义的,以确保这些提供者可以在应用之间或应用内部被唯一地识别。以下是如何为 FileProvider 设置 android:authorities 的步骤:
-
定义
FileProvider:在你的
AndroidManifest.xml文件中,在<application>标签内添加<provider>标签来定义FileProvider。 -
设置
android:name:将
android:name属性设置为androidx.core.content.FileProvider(如果你使用的是 AndroidX 库)或者android.support.v4.content.FileProvider(如果你使用的是 Support Library)。 -
设置
android:authorities:为
android:authorities属性提供一个唯一的字符串值。通常这个值会基于你的应用的包名,并加上一个自定义的后缀。例如,如果你的包名是com.example.myapp,那么你可以将android:authorities设置为com.example.myapp.provider。 -
设置
android:exported和android:grantUriPermissions:对于
FileProvider,通常将android:exported设置为false(除非你有特殊需求),并将android:grantUriPermissions设置为true以允许接收Intent的应用访问由FileProvider提供的文件。 -
添加
meta-data:在
<provider>标签内添加一个<meta-data>标签,用于指定FileProvider可以访问的文件路径的 XML 资源文件。
以下是一个完整的示例:
xml复制代码
|---|-------------------------------------------------------------------------|
| | <manifest xmlns:android="http://schemas.android.com/apk/res/android" |
| | package="com.example.myapp"> |
| | |
| | <application |
| | ... > |
| | |
| | <!-- 其他组件 --> |
| | |
| | <provider |
| | android:name="androidx.core.content.FileProvider" |
| | android:authorities="com.example.myapp.provider" |
| | android:exported="false" |
| | android:grantUriPermissions="true"> |
| | <meta-data |
| | android:name="android.support.FILE_PROVIDER_PATHS" |
| | android:resource="@xml/file_paths" /> |
| | </provider> |
| | |
| | <!-- 其他组件 --> |
| | |
| | </application> |
| | |
| | </manifest> |
在这个示例中,@xml/file_paths 是指向 res/xml/file_paths.xml 文件的引用,该文件应该包含你想要通过 FileProvider 共享的文件的路径。
file_paths.xml 的内容可能如下所示:
xml复制代码
|---|-------------------------------------------------------------------------|
| | <paths xmlns:android="http://schemas.android.com/apk/res/android"> |
| | <files-path name="my_images" path="images/"/> |
| | <external-files-path name="external_images" path="Pictures/MyApp/"/> |
| | <!-- 其他路径定义 --> |
| | </paths> |
这个示例定义了两个路径:一个是应用内部文件目录中的 images/ 子目录,另一个是外部存储中的 Pictures/MyApp/ 目录。你可以根据你的需求添加或修改这些路径。