IntentFilter匹配规则

本文详细介绍了Android中IntentFilter的匹配规则,包括Action、Category和Data的测试。在隐式Intent启动Activity时,Intent需要与AndroidManifest.xml中声明的Intent-Filter匹配。Action必须匹配,Category至少匹配一个,Data部分则涉及URI和MIME类型的比较。通过示例代码展示了如何创建和匹配Intent,强调了在使用隐式Intent时确保有符合条件的Activity,否则可能导致应用崩溃。
摘要由CSDN通过智能技术生成

1、Intent types

Intent有两种类型,显式Intent和隐式Intent。

使用显式Intent启动的目标组件特别明确,而隐式Intent则需要能够匹配组件在AndroidManifest.xml中声明的<intent-filter>信息。

2、Intent Filter

当通过隐式Intent启动Activity时,该Intent需要同时匹配Activity在AndroidManifest.xml中声明的<intent-filter>中的<action>、<data>和<category>信息,否则匹配失败。(必须是<action>、<data>、<category>三者都匹配才算匹配成功)

2-1、Action test

<intent-filter>
    <action android:name="android.intent.action.EDIT" />
    <action android:name="android.intent.action.VIEW" />
    ...
</intent-filter>

<intent-filter>中可以声明0或者多个<action>元素。

Intent中的Action必须能与<intent-filter>中声明的<action>之一匹配。(匹配是指<action>字符串相等,区分大小写。)

如果Intent-Filter中未声明任何<action>,则任何Intent都将匹配失败。但是,如果Intent中未声明Action,则该Intent可以匹配有<action>的Intent-Filter(只要有<action>声明即可,无论声明的是什么)。

2-2、Category test

<intent-filter>
    <category android:name="android.intent.category.DEFAULT" />
    <category android:name="android.intent.category.BROWSABLE" />
    ...
</intent-filter>

<intent-filter>中可以声明0或者多个<category>元素。

Intent中的每一个Category必须能与<intent-filter>中的某一<category>匹配。如果Intent中没有Category,则总成是匹配成功(不管<intent-filter>中声明了什么<category>--未声明任何<category>或声明有<category>)。

注意:Android对于传入startActivity()和startActivityForResult()的隐式Intent会自动加入CATEGORY_DEFAULT category,所以如果某个Activity要想能够响应隐式Intent,则必须要在<intent-filter>中声明“android.intent.category.DEFAULT” cateogry。

2-3、Data test

<intent-filter>
    <data android:mimeType="video/mpeg" android:scheme="http" ... />
    <data android:mimeType="audio/mpeg" android:scheme="http" ... />
    ...
</intent-filter>

<intent-filter>中可以声明0或者多个<data>元素。

每个<data>元素由URI和mimeType两部分组成。URI由scheme,host,port和path属性组成。

<scheme>://<host>:<port>/<path>

content://com.example.project:200/folder/subfolder/etc

scheme:content
host:com.example.project
port:200
path:folder/subfolder/etc

URI中的这些属性都是可选的,但是存在线性依赖关系:

  • If a scheme is not specified, the host is ignored.
  • If a host is not specified, the port is ignored.
  • If both the scheme and host are not specified, the path is ignored.

当Intent中的URI与<intent-filter>中的URI匹配时,仅比较<intent-filter>URI中声明的属性部分,如果Intent中的URI属性能够与<intent-filter>中声明的属性都匹配,则认为匹配成功,如:

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值