Android IntentFilter 匹配规则

  • Android,intent,intentfilter,

文章已迁移至 https://binkery.com/archives/2020.09.25-android-intent-filter-rules.html

Intent 是 Android 组件相互沟通的信息载体。一个 Intent 由一个组件发出。如果这个 intent 是一个显示 Intent 的话,也就是这个 Intent 有明确的接收者,系统会把这个 Intent 交给这个指定的组件。如果这是一个隐式的 Intent ,没有指明确却的接收者,那么,系统就通过各个组件的注册信息来决定需要把 Intent 分发给哪些组件。

四大组件都需要在 manifest 文件中注册,注册的时候可以选择性的添加 intent-fliter,也就是咱们现在要讨论的 Intent 过滤器。

NOTE:四大组件中,Content Provider 注册的时候是没有 Intent Filter 的。

下面是咱们最常见的一个过滤器,每个 Android 应用基本上都有这么一个。添加了这么一个 intent filter 的 Activity 被认为是这个应用的入口,并且启动器会在应用列表中列出这个应用。

<intent-filter>
    <action android:name="android.intent.action.MAIN" />
    <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

每个组件都可以添加多个 Intent Filter 。

在一个 IntentFilter 判断是否匹配某一个 Intent 的时候, 有三个条件必须符合: 动作(action),分类(category) , 数据(data)。如果特别指定的话,数据包括数据类型(data type)和数据(data scheme+authority+path)。IntentFilter.match(ContentResolver, Intent, boolean, String)有更多数据匹配的细节。

Intent Filter 的属性

<intent-filter/> 有三个属性。

  • android:icon : 一个图标
  • android:label : 一个文本
  • android:priority : 优先级。取值从 -1000 到 100,可以影响到 Activity 和 Broadcast Receiver 。

Action

<action android:name="com.xxx.xxx.XXX_XXX" />

Data

语法:

 <data android:scheme="string"
      android:host="string"
      android:port="string"
      android:path="string"
      android:pathPattern="string"
      android:pathPrefix="string"
      android:mimeType="string" />

一个 URI 的组成如下,<data/> 的各个属性分别与 URI 对应。

<scheme>://<host>:<port>[<path>|<pathPrefix>|<pathPattern>]

一个 <intent-filter/> 可以包含多个 <data/> 标签,把多个标签不同的属性组合到一个标签,效果是一样的。

<intent-filter . . . >
    <data android:scheme="something" android:host="project.example.com" />
    . . .
</intent-filter>
<intent-filter . . . >
    <data android:scheme="something" />
    <data android:host="project.example.com" />
    . . .
</intent-filter>

android:scheme

协议名,比如 http,ftp,content,file 等,以及很多时候,这个地方可以是自定义的。必须使用小写,不能使用 HTTP 这样的。

If the filter has a data type set (the mimeType attribute) but no scheme, the content: and file: schemes are assumed.

android:host

主机地址,也是需要全小写。

android:port

端口号。这个属性不应该单独出现,需要同时有 scheme 和 host 属性。

android:path & android:pathPrefix & android:pathPattern

路径匹配规则。

  • 如果定义了 android:path ,必须路径完全匹配。
  • 如果定义了 android:pathPrefix ,路径的前部分要匹配。
  • 如果定义了 android:pathPattern ,模糊匹配,可以通过 * 号来模糊匹配。

路径匹配规则也不能单独出现,需要有 scheme 和 host 属性。三个路径规则不能同时出现。

android:mimeType

MIME media type,定义文件的类型,比如 image/jpeg,也可以使用 image/ 来表示所有图片格式的文件。也可以使用 /* 来表示所有文件。

category

语法:

<category android:name="string" />

属性:

android:name

分类的名字,标准的分类定义在 Intent 类中,以 CATEGORY_name 名字开头的常量。

为了接收到一个隐性的 Intent ,在 intent-filter 中必须包含 android.intent.category.LAUNCHER 这个分类。

如果需要自定义分类,一般以包名作为前缀,以确保分类名字唯一。

相关文章

- EOF -

本站文章除注明转载外,均为本站原创或编译。欢迎任何形式的转载,但请务必注明出处,尊重他人劳动。
转载请注明:文章转载自 Binkery 技术博客 [https://binkery.com]
本文标题: Android IntentFilter 匹配规则
本文地址: https://binkery.com/archives/420.html