当前位置:   article > 正文

IntentFilter详解_intent-filter

intent-filter

IntentFilter的意思就是意图过滤器,当我们隐式的启动系统组件的时候,就会根据IntentFilter来筛选出合适的进行启动。

如果组件的 IntentFilter 与 Intent 中的 IntentFilter 正好匹配,系统就会启动该组件,并把 Intent 传递给它。如果有多个组件同时匹配到了,系统则会弹出一个选择框,让用户选择使用哪个应用去处理这个 Intent,比如有时候点击一个网页链接,会弹出多个应用,让用户选择用哪个浏览器去打开该链接,就是这种情况。


我们都知道,Intent 可以分为两种类型,分别为显示和隐示。
显示的调用也就是常使用的:

Intent intent = new Intent(context,Activity.class);
startActivity(intent);
  • 1
  • 2

相信这种用法我们并不陌生。
对于隐式的调用方式,我们在创建项目的时候也就自动添加了,如在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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

intent-filter标签中,可配置的选项有三个,分别是:

  • action:用来表示意图的行动,这个可以自定义也可以使用系统中自带的 Action 值。上面的android.intent.action.MAIN,标识 该Activity 为这个APP的开始。
  • category:声明接受的Intent类别。
  • data:根据设置的数据匹配,通常为Uri类型。

在使用时候,通常为在配置文件AndroidManifest.xml中配置Activity的过滤规则,然后使用IntentActivity中:

Intent intent = new Intent();
intent.setAction(Intent.ACTION_BATTERY_LOW);
intent.addCategory(Intent.CATEGORY_APP_EMAIL);
intent.setDataAndType(Uri.EMPTY, "video/mpeg");
startActivity(intent);
  • 1
  • 2
  • 3
  • 4
  • 5

1. <action/>

首先IntentFilter中可以有多个actionIntent最多能有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中的其中一个(区分大小写)。

2. <category />

首先IntentFilter中可以有多个categoryIntent也可以有多个。

(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 />将不会导致匹配失败。

在这里插入图片描述

3. <data>

首先IntentFilter可以有多个dataIntent最多能有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" />
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

一个data主要包括的就是URImimeTypemimeType表示媒体类型,其余都属于URI。在Intent中可以设置这两部分的数据,比如:

intent.setDataAndType(Uri, "text/plain");
  • 1

IntentFilterIntent中的data必须完全匹配才能通过,也适用于通配符。


  1. https://www.cnblogs.com/Jeely/p/11046438.html
  2. https://www.jianshu.com/p/a2f826064e29
  3. https://blog.csdn.net/madreain/article/details/90730431
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/236127
推荐阅读
相关标签
  

闽ICP备14008679号