Search code examples
androidandroid-intentnfcintentfilterndef

NFC type default app


I just started working with NFC. When scanning an NFC tag my app opens by default but I have 2 issues:

  1. For some reason I can't see my app in launcher app browser.

  2. How can I define to open the app only when NFC is URL type?

    <uses-permission android:name="android.permission.NFC" />
    <uses-feature android:name="android.hardware.nfc" android:required="true" />
    
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
    
            <activity android:name=".MainActivity">
            <intent-filter>
    
                <action android:name="android.nfc.action.NDEF_DISCOVERED" />
                <category android:name="android.intent.category.DEFAULT" />
                <data android:mimeType="text/plain" />
    
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <meta-data
                android:name="android.nfc.action.TECH_DISCOVERED"
                android:resource="@xml/nfc_tech_filter" />
        </activity>
    </application>
    


Solution

  • The first problem (app not shown in launcher) is due to the way multiple filter criteria are combined within one <intent-filter> section (see Intents and Intent Filters. You can easily overcome this by splitting your intent filters into separate <intent-filter> sections:

    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
    <intent-filter>
        <action android:name="android.nfc.action.NDEF_DISCOVERED" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:mimeType="text/plain" />
    </intent-filter>
    

    The second problem depends on what data (NDEF records) you stored on the tag. If, for instance, you stored a URI record containing the URL https://stackoverflow.com/, you would use the following intent filter:

    <intent-filter>
        <action android:name="android.nfc.action.NDEF_DISCOVERED" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:scheme="https" android:host="stackoverflow.com" />
    </intent-filter>
    

    You might also want to check