Launch Specific App when NFC is discovered

匆匆过客 提交于 2019-12-01 22:46:09
Michael Roland

The reason why you get an intent chooser is that multiple activities are registered for the data type text/plain. This is a rather common case and you should therefore avoid using such generic data types for the NDEF record that should launch your activity. You have two options to overcome this problem:

  1. Use an NFC Forum external type for your NDEF record (this is what ThomasRS already mentioned). With this method you create a custom record type that is meaningful to your application only. You can create such a record (to write it to your tag or to send over Beam) with something like this:

    NdefRecord extRecord = NdefRecord.createExternal(
            "yourdomain.com",  // your domain name
            "yourtype",        // your type name
            textBytes);        // payload
    

    You can then register your activity to launch upon this record like this:

    <activity ...>
        <intent-filter>
            <action android:name="android.nfc.action.NDEF_DISCOVERED" />
            <category android:name="android.intent.category.DEFAULT" />
            <data android:scheme="vnd.android.nfc" android:host="ext"
                  android:pathPrefix="/yourdomain.com:yourtype" />
        </intent-filter>
    </activity>
    
  2. Use an Android Application Record (AAR). An AAR will make sure that the NDEF_DISCOVERED intent is delivered to an app with a specific package name only. You can create such a record (to write it to your tag or to send over Beam) with something like this:

    NdefRecord appRecord = NdefRecord.createApplicationRecord(
            "com.yourdomain.yourapp");
    NdefRecord textRecord = NdefRecord.createTextRecord(
            "en",       // language code
            "yourtext"  // human-readable text);
    NdefMessage msg = new NdefMessage(
            textRecord,
            appRecord);  // use the AAR as the *last* record in your NDEF message
    

Use the External Type NDEF record with your own domain and give your app a corresponding intent-filter.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!