IntentFilter匹配

作者: waiwaaa | 来源:发表于2018-08-31 19:58 被阅读23次

    Intent不应该同时存在显示调用及隐示调用,同时存在时以显示调用为准 。隐式调用需要Intent能够匹配目标组件的IntentFilter中所设置的过滤信息,如果不匹配将无法启动目标组件。

    IntentFilter的过滤信息有:action, category, data 。

    匹配规则:

    • 需同时匹配过滤列表中的action, category, data信息,否则匹配失败
    • 一个过滤列表中action, category, data可以有多个,一个Activity可以有多个IntentFilter
    • 一个Intent只要能匹配任何一组IntentFilter就可以成功启动组件

    各属性的匹配规则:

    action的匹配规则

    • action是一个字符串,可以是系统预定义的,也可以定义自己的
    • 匹配是指完全相同,区分大小写。
    • 只要能够和过滤规则中任何一个action匹配即可匹配成功。
    • 如果Intent没有指定 action,那么失败。

    category的匹配规则

    • category是一个字符串,可以是系统预定义的,也可以定义自己的
    • Intent中category可以有多个,每一个都必须与过滤规则中的一个category相同
    • 如果Intent中没有设置category,默认会加上android.intent.category.DEFAULT这个categroy
    • 为了组件能接收隐式调用,就必须在intent-filter中指定android.intent.category.DEFAULT这个categroy(由于上面原因)

    data的匹配规则

    • Intent中必须有data,data数据能完全匹配过滤规则中的某个data
    • data语法
    <data android:scheme="string"
        android:host="string"
        android:port="string"
        android:path="string"
        android:pathPattern="string"
        android:pathPrefix="string"
        android:mimeType="string"/>
    

    data由mimeType 和 URI 两部分组成。

    mimeType指媒体类型,如image/jpeg、audio/meeg4-generic和video/*等
    URI结构:
    <sheme>://<host>:<port>/[<path>|<pathPrefix>|<pathPattern>]

    URI如果没有指定,schema默认值为content和file。
    为Intent指定完整的data,必须调用setDataAndType方法,不能调用setData后再试用setType,因为两个方法会相互清空对方的值。

    其它

    • 入口intent-filter
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
    
    • 判断是否有Activity可以匹配隐式Intent
      intent.resolveActivity(PackageManager pm)返回null表示找不到匹配
    PackageManager pManager = this.getPackageManager();
    List<ResolveInfo> list=pManager.queryIntentActivities(intent,flags);
    if(list==null){
    //没有找到匹配的
    }
    
    ResolveInfo rf=pManager.resolveActivity(intent,flags);
    if(rf==null){
    //没有找到匹配的
    }
    

    flags指定MATCH_DEFAULT_ONLY这个标志位,仅匹配intent-filter中声明了<category android:name="android.intent.category.DEFAULT"/>这个category的Activity。用此参数,如果查出的不为空,一定成功。

    相关文章

      网友评论

        本文标题:IntentFilter匹配

        本文链接:https://www.haomeiwen.com/subject/wjfewftx.html