intent filter without action

2019-02-20 15:47发布

Android's documentation says:

http://developer.android.com/reference/android/content/IntentFilter.html

"Action matches if any of the given values match the Intent action, or if no actions were specified in the filter."

I just tried to test it. In my test application I set such filter for one of activities:

<intent-filter>
    <action android:name="ma" />
    <category android:name="android.intent.category.DEFAULT" />
    <category android:name="mk1" />
</intent-filter>

I try to send such intent:

Intent i = new Intent();
i.setAction("ma");
i.addCategory("mk1");
startActivity(i);

It works - my activity gets started.

Then I comment out action in filter:

<intent-filter>
    <!-- <action android:name="ma" /> -->
    <category android:name="android.intent.category.DEFAULT" />
    <category android:name="mk1" />
</intent-filter>

Again I send the very same intent. Now my activity doesn't start.

Why? According to documentation, when my filter has no actions specified, intent with some actions should fullfill it.

2条回答
倾城 Initia
2楼-- · 2019-02-20 15:49

Refer to the documentation on IntentFilters especially the following description of the action test in the section on Intent Resolution:

As the example shows, while an Intent object names just a single action, a filter may list more than one. The list cannot be empty; a filter must contain at least one element, or it will block all intents.

To pass this test, the action specified in the Intent object must match one of the actions listed in the filter. If the object or the filter does not specify an action, the results are as follows:

  • If the filter fails to list any actions, there is nothing for an intent to match, so all intents fail the test. No intents can get through the filter.

  • On the other hand, an Intent object that doesn't specify an action automatically passes the test — as long as the filter contains at least one action.

It is pretty clear from this that an IntentFilter that contains no actions will not match any Intent objects. Which is what you are seeing.


On the other hand, I absolutely agree with you that the documentation is inconsistent. Even the section I copied here is inconsistent, as it states both "a filter must contain at least one element, or it will block all intents" and also "an Intent object that doesn't specify an action automatically passes the test — as long as the filter contains at least one action."

查看更多
成全新的幸福
3楼-- · 2019-02-20 16:10

You should also comment i.setAction("ma"); in your source.

查看更多
登录 后发表回答