Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read and write to a NfcA card from Android

Tags:

android

nfc

I've made an app that is called when the intent android.nfc.action.TAG_DISCOVERED is sent, but then I want to get the info of the card in the onNewIntent method, but I don't know how to handle this kind of nfc cards. I tried with the following code:

    public void onNewIntent(Intent intent) {
        Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        //do something with tagFromIntent
        NfcA nfca = NfcA.get(tagFromIntent);
        try{
            nfca.connect();
            Short s = nfca.getSak();
            byte[] a = nfca.getAtqa();
            String atqa = new String(a, Charset.forName("US-ASCII"));
            tv.setText("SAK = "+s+"\nATQA = "+atqa);
            nfca.close();
        }
        catch(Exception e){
            Log.e(TAG, "Error when reading tag");
            tv.setText("Error");
        }
    }

tv is a TextView, but when this code is executed it never gets changed.

like image 878
susomena Avatar asked Oct 21 '22 22:10

susomena


People also ask

What is NFC tag on Android?

Near Field Communication (NFC) is a set of short-range wireless technologies, typically requiring a distance of 4cm or less to initiate a connection. NFC allows you to share small payloads of data between an NFC tag and an Android-powered device, or between two Android-powered devices. Tags can range in complexity.


1 Answers

OnNewIntent is called if your activity is already running and is set to be singleTask. You'll want to make the code it's own method and call it in onCreate() as well as onNewIntent()

like image 148
MrChaz Avatar answered Nov 01 '22 14:11

MrChaz