简体   繁体   中英

NFC tag reading problem

This is my code to read the NFC tag. Why authentication is failing always? It is detecting the card but not reading the data. Could you please help me? Why if block is not executing? Where i'am wrong?

void resolveIntent(Intent intent)
{ 
String action = intent.getAction();

if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(action))
{ 
    Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);

    MifareClassic mfc = MifareClassic.get(tagFromIntent); 
    byte[] data;

    try
    {    
        mfc.connect();
        boolean auth = false;
        String cardData = "";

        int sectorCount = mfc.getSectorCount();
        int blockCount = 0;
        int blockIndex = 0;
        for(int j = 0; j < sectorCount; j++)
        { 
            auth = mfc.authenticateSectorWithKeyA(j, MifareClassic.KEY_DEFAULT);
            if(auth)
            {

                blockCount = mfc.getBlockCountInSector(j);
                blockIndex = 0;
                for(int i = 0; i < blockCount; i++)
                {
                    blockIndex = mfc.sectorToBlock(j);

                    data = mfc.readBlock(blockIndex);    

                    cardData = cardData + getHexString(data, data.length);
                    blockIndex++;
                }
            }

            else
            { 
                // Authentication failed - Handle it
                showAlert(AUTH); //this alert message is executing always
            }
        } 
        Toast.makeText(getApplicationContext(), cardData, Toast.LENGTH_LONG).show();
    }
    catch (IOException e)
    { 
        Log.e(TAG, e.getLocalizedMessage());
        showAlert(NETWORK);
    }
   }//end of if
}// End of method

Since it is not a new tag, and has been written by another app, I would suspect that the authentication key has changed. You are using the default keys, but the other app may have changed them. The older Nokia phones do this all the time. In that case instead of using MifareClasic.KEY_DEFAULT, you will need to figure out what the new key is for keyA

尝试使用MifareClassic.KEY_NFC_FORUM作为keyA

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM