赞
踩
IntentFilter
的意思就是意图过滤器,当我们隐式的启动系统组件的时候,就会根据IntentFilter
来筛选出合适的进行启动。
如果组件的 IntentFilter 与 Intent 中的 IntentFilter 正好匹配,系统就会启动该组件,并把 Intent 传递给它。如果有多个组件同时匹配到了,系统则会弹出一个选择框,让用户选择使用哪个应用去处理这个 Intent,比如有时候点击一个网页链接,会弹出多个应用,让用户选择用哪个浏览器去打开该链接,就是这种情况。
我们都知道,Intent
可以分为两种类型,分别为显示和隐示。
显示的调用也就是常使用的:
Intent intent = new Intent(context,Activity.class);
startActivity(intent);
相信这种用法我们并不陌生。
对于隐式的调用方式,我们在创建项目的时候也就自动添加了,如在AndroidManifest.xml
文件中:
<activity android:name=".TestActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
在intent-filter
标签中,可配置的选项有三个,分别是:
Action
值。上面的android.intent.action.MAIN
,标识 该Activity
为这个APP
的开始。Intent
类别。Uri
类型。在使用时候,通常为在配置文件AndroidManifest.xml
中配置Activity
的过滤规则,然后使用Intent
在Activity
中:
Intent intent = new Intent();
intent.setAction(Intent.ACTION_BATTERY_LOW);
intent.addCategory(Intent.CATEGORY_APP_EMAIL);
intent.setDataAndType(Uri.EMPTY, "video/mpeg");
startActivity(intent);
首先IntentFilter
中可以有多个action
,Intent
最多能有1
个。
(1) 如果<intent-filter>
标签中有多个<action/>
,那么Intent
请求的Action
,只要匹配其中的一条<action/>
就可以通过了这条<intent-filter>
的动作测试。
(2) 如果<intent-filter>
中没有<action/>
,那么无论什么Intent
请求都无法和这条<intent-filter>
匹配。
(3) 如果<intent-filter>
中有<action/>
,若intent
中不存在action
,那么可以通过;如果intent
中存在action
,那么intent
中的action
必须是IntentFilter
中的其中一个(区分大小写)。
首先IntentFilter
中可以有多个category
,Intent
也可以有多个。
(1)如果IntentFilter
不存在category
,那么所有的intent
都无法通过。有一个例外,Android
把所有传给startActivity()
的隐式意图当作他们包含至少一个类别:"android.intent.category.DEFAULT"
。 因此,想要接收隐式意图的活动必须在它们的意图过滤器中包含"android.intent.category.DEFAULT"
。
(2)如果IntentFilter
存在category
,如果intent
中不存在存在category
,可以通过。如果intent
中存在,那么intent
中的所有category
都包含在IntentFilter
中,才可以通过。
即:Intent
中的类别必须全部匹配<intent-filter>
中的<category />
,但是<intent-filter>
中多余的<category />
将不会导致匹配失败。
首先IntentFilter
可以有多个data
,Intent
最多能有1
个。
<data>
元素指定了可以接受的Intent
传过来的数据URI
和数据类型
,当一个意图对象中的URI
被用来和一个过滤器中的URI
比较时,比较的是URI
的各个组成部分。举个例子:
<data android:mimeType="text/plain"
android:host="www.mathiasluo.com"
android:path="/myfolder/my.txt"
android:pathPattern="/myfolder/*"
android:port="80"
android:scheme="http" />
一个data
主要包括的就是URI
和mimeType
。mimeType
表示媒体类型,其余都属于URI
。在Intent
中可以设置这两部分的数据,比如:
intent.setDataAndType(Uri, "text/plain");
IntentFilter
和Intent
中的data
必须完全匹配才能通过,也适用于通配符。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。