Launch Specific App when NFC is discovered

后端 未结 2 744
醉梦人生
醉梦人生 2021-01-22 16:20

I am using NFC in my app and it is working fine. However I want to make sure that only my app is launched and no other App is there to handle the intent. Following is the code f

2条回答
  •  孤城傲影
    2021-01-22 16:47

    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:

      
          
              
              
              
          
      
      
    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
      

提交回复
热议问题