NFC Tag Reading

前端 未结 2 945
醉梦人生
醉梦人生 2020-12-02 02:57

I got an application that reads and writes nfc tags with ndef data format. This all seems to be ok. But whenever i try to get closer a tag to my phone, it produces a new act

相关标签:
2条回答
  • 2020-12-02 03:53

    Instead of setting the launch-mode of the activity that receives the NFC intents to "singleTask" (see CommonsWare's answer), the preferred way for NFC applications to receive NFC-related intents while the app is in foreground is the foreground dispatch system (or alternatively the reader mode API when using only Android 4.4).

    In order to use the foreground dispatch, you would create a pending intent like this:

    PendingIntent pendingIntent = PendingIntent.getActivity(
        this,
        0,
        new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),
        0);
    

    Then, in your activity's onResume() method, you would enable the foreground dispatch like this:

    NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
    nfcAdapter.enableForegroundDispatch(this, pendingIntent, null, null);
    

    You will then receive intents notifying you about discovered tags through the activity's onNewIntent() method:

    public void onNewIntent(Intent intent) {
        ...
    }
    

    Moreover, you have to disable the foreground dispatch in your activity's onPause() method:

    NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
    nfcAdapter.disableForegroundDispatch(this);
    
    0 讨论(0)
  • 2020-12-02 03:55

    Add android:launchMode="singleTask" to the <activity> element for MainActivity. Note that if the activity is already running, onNewIntent() will be called, instead of onCreate(), to deliver the NDEF Intent to you. Hence, you will need to handle the NDEF Intent in both onCreate() (if the activity was not already running) and onNewIntent() (if the activity was already running).

    This sample project illustrates the technique.

    0 讨论(0)
提交回复
热议问题