Just read an NFC tag

后端 未结 2 1199
梦谈多话
梦谈多话 2021-02-11 00:38

I am developing an app that will use NFC tags for identification. All examples I find however, are about starting an app when a certain card is read. I tried looking for an exam

相关标签:
2条回答
  • 2021-02-11 01:01

    I found part of the answer here: NFC broadcastreceiver problem

    That solution doesn't provide a complete working example, so I tried a little extra. To help future visitors, I'll post my solution. It is a NfcActivity which subclasses Activity, if you subclass this NfcActivity, all you have to do is implement its NfcRead method, and you're good to go:

    public abstract class NfcActivity extends Activity  {
        // NFC handling stuff
        PendingIntent pendingIntent;
        NfcAdapter nfcAdapter;
    
        @Override
        public void onResume() {        
            super.onResume();
    
            pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
                    getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
    
             nfcAdapter = NfcAdapter.getDefaultAdapter(this);
             nfcAdapter.enableForegroundDispatch(this, pendingIntent, null, null);
        }
    
        @Override
        protected void onPause() {
            super.onPause();
            nfcAdapter.disableForegroundDispatch(this);
        }
    
        // does nothing, has to be overridden in child classes
        public abstract void NfcRead(Intent intent);
    
        @Override
        public void onNewIntent(Intent intent) {
            String action = intent.getAction();
    
            if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)) {
                NfcRead(intent);            
            } 
        }
    }
    
    0 讨论(0)
  • 2021-02-11 01:18

    If you want that the user first starts your app and only then scans an NFC card, I would recommend using NFC foreground dispatch. In that way, your Activity does not need to have any intent filters in the manifest (and thus will never be called by accident when the user scans another NFC card). With foreground dispatch enabled, your Activity can receive all NFC intents directly (without any app chooser pop-ups) and decide what to do with it (e.g. pass it on to another Activity).

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