详解Android中Intent对象与Intent Filter过滤匹配过程

2019-12-10 19:42:54于海丽

以下intent对象无法通过category测试

Intent intent = new Intent();
intent.setAction("com.ispring.action.ACTION_TEST1");
intent.addCategory("com.ispring.category.TEST1");
intent.addCategory("com.ispring.category.TEST3");

该intent之所以无法通过上面的intent-filter的category测试是因为intent-filter只包含了该intent中值为com.ispring.category.TEST1的category,而并未包含值为com.ispring.category.TEST3的category,不满足完全包含intent中全部category的情况。

  • intent对象不包含任何category

    如果intent对象没有调用过addCategory()方法,那么intent对象就不包含任何的category。这种情形下,如果该intent不是用来启动Activity的话,那么无论intent-filter中category中如何配置,intent对象总是能通过intent-filter的category测试,即便intent-filter中没有声明任何的category,intent都能通过category测试。此处强调了该intent不是用来启动Activity这种条件,会在下面详细解释。

    此处需要特别说明的是,我们在上面所有的示例中,都给Activity的intent-filter添加了值为android.intent.category.DEFAULT的category,这是因为当我们把一个隐式的intent传递给startActivity()或startActivityForResult()方法时,Android会自动给该隐式intent添加值为android.intent.category.DEFAULT的category,所以为了能让intent-filter包含intent中全部的category,我们就需要在Activity的intent-filter中添加该category,在使用时需要特别注意。

    根据上面我们的几个示例,我们总结如下: 

    1. 如果intent对象不包含任何category,并且该intent不是用来启动Activity的,那么该intent对象总是能通过所有任意的intent-filter的category测试; 
    2. 如果intent对象包含category(至少一个),那么只有当intent-filter中声明的category全部包含intent对象中的所有category的时候才通过category测试。 
    3. 如果允许Activity被隐式的Intent启动,那么我们必须在该Activity的intent-filter中声明值为android.intent.category.DEFAULT的category。

    Data测试

    为了指定可以接收的Intent的data,intent-filter需要声明0个多多个<data />标签,例如: