AndroidMainfest - should an intent-filter have mul

2019-06-17 01:33发布

问题:

My current intent-filter for my MainActivity looks like this

<intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
                <action android:name="android.hardware.usb.action.USB_ACCESSORY_ATTACHED" />
            </intent-filter>

Notice that there are 2 action nodes. Is this correct? Or should there only be one action node per intent-filter?

Also, what is the purpose of the DEFAULT category?

<category android:name="android.intent.category.DEFAULT" />

回答1:

Is this correct?

It can be, though in this case I suspect it is not what you want.

This <intent-filter> will match:

  • an Intent with the MAIN action and the LAUNCHER category, or

  • an Intent with the USB_ACCESSORY_ATTACHED and the LAUNCHER category

The former is common. However, I rather doubt that USB_ACCESSORY_ATTACHED will be used with the LAUNCHER category. I am not even sure it is used with activities, as the documentation is a bit muddled on this point.



回答2:

A intent filter can have n number of actions based on your activity need. For instance if your application receives one or multiple images from a social sharing app then you would use

<action android:name="android.intent.action.SEND"/>
<action android:name="android.intent.action.SEND_MULTIPLE"/>

For reference look at the Example Filters section of this article.



回答3:

An intent filter can apply to many actions. But it means in the receiving code you will need to check which intent action was activated. For example:

 <action android:name="android.intent.action.VIEW" />
 <action android:name="android.nfc.action.NDEF_DISCOVERED" />

Such as

boolean ndefAction = NfcAdapter.ACTION_NDEF_DISCOVERED.equals (intent.getAction ());


回答4:

yes, from docs for <action> element:

http://developer.android.com/guide/topics/manifest/action-element.html

Adds an action to an intent filter. An element must contain one or more elements. If it doesn't contain any, no Intent objects will get through the filter. See Intents and Intent Filters for details on intent filters and the role of action specifications within a filter.



回答5:

I tested it and it won't work without adding DEFAULT inside category.

<intent-filter>
   <action android:name="android.intent.action.MAIN" />
   <action android:name="android.hardware.usb.action.USB_ACCESSORY_ATTACHED" />
   <category android:name="android.intent.category.LAUNCHER" />
   <category android:name="android.intent.category.DEFAULT" /> <!--This is required-->
</intent-filter>