您的位置:首页 > 其它

IntentFilter 匹配的一些事

2016-05-26 17:10 274 查看

启动Activity的两种方式

显示调用

就像我们平时用的最多的

startActivity(new Intent(this,XXXActivity.class);

隐示调用

就是通过匹配IntentFilter中设置的过滤信息进行调用。下面主要是匹配的方式和规则

IntentFilter 的过滤信息

action

一个字符串,可以自定义,一般会结合包名。

category

一个字符串,可以自定义,一般会结合包名。

data

两部分组成,mimeType和URI。mimyType指的是媒体类型,比如image/jpeg,audio/mpeg4-generic和video/*等,表示图片文本视频等不同格式,而URI有特定结构:

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

scheme:URI的模式,比如http,ftp,file,必须指定
host:URI的主机名,比如www.baidu.com,必须指定
port:URI的端口号,比如80,当前两者均指定时才有效
path等:表示路径信息

例子:http://www.baidu.com:80/search/info


IntentFilter 的过滤规则

action

Intent中的action必须能够和filter中的字符串值完全一样,并且只需要匹配其中一个。ps 如果在intent中没有指定action则匹配失败。

category

Intent中的所有category必须在filter中已经存在。ps 不设置category也可以匹配成功,因为系统在调用startActivity或startActivityForResult的时候会默认在intent加上“android.intent.category.DEFAULT”,当然前提是想要隐式调用必须在filter规则上加上DEFAULT这个category。

data

data的匹配规则和action类似,它也要求intent中必须含有data数据,并且能完全匹配filter中的某一个data.

如下filter规则

<intent-filter>
<data android:mimeType="image/*"/>
...
</intent-filter>


这种规则虽然没有指定URI ,却有默认值,URI的默认值为content和file,也就是说,scheme部分必须为content和file才能匹配!为此可以写出如下示例

intent.setDataAndType(Uri.parse("file://abc"),"image/png");


完整的匹配例子

filter规则:

<activity
android:name="com.example.FirstActivity:
android:launchMode="singleTask"
<intent-filter>
<action android:name="com.example.action.a"/>
<action android:name="com.example.action.b"/>
<category android:name="com.example.category.a"/>
<category android:name="com.example.category.b"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="text/plain"/>
</intent-filter>
</activity>


匹配:

Intent intent = new Intent("com.example.action.a");
intent.addCategory("com.example.category.a");
intent.setDataAndType(Uri.parse("file://abc"),"text/plain");
startActivity(intent);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: