2017-08-15 50 views
2

我正在开发需要读取NFC卡(卡技术是NFC-F)的Android应用程序。在那里,我总是得到以下异常:TagLostException当在Android上读取NFC-F卡时

android.nfc.TagLostException:标记丢失。

这里是我的代码:

private void handleIntent(Intent intent) { 
    String action = intent.getAction(); 
    if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) { 

    } else if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)) { 

    } else if(NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)) { 

     Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); 
     if (tag != null) { 
      NfcF nfcf = NfcF.get(tag); 
      try { 
       nfcf.connect(); 
       byte[] AUTO_POLLING_START = {(byte) 0xE0, 0x00, 0x00, 0x40, 0x01}; 
       byte[] response = nfcf.transceive(AUTO_POLLING_START); 
       nfcf.close(); 
      } catch (Exception e) { 
       e.printStackTrace(); 
       mTextView.setText(e.toString()); 
      } 
     } 
    } 
} 

谁能帮助我对这个问题?

+0

改进的格式 –

回答

0

您收到TagLostException,因为您向标签发送了无效命令。由于NFC-F标签在接收到无效命令时保持沉默,Android无法区分实际通信丢失或对不支持/无效命令的否定响应,并且在两种情况下均抛出TagLostException

有效的FeliCa(NFC-F)命令有

 
+----------+----------+------------------+-----------------------------------------------+ 
| LEN  | COMMAND | IDm    | PARAMETER          | 
| (1 byte) | (1 byte) | (8 bytes)  | (N bytes)          | 
+----------+----------+------------------+-----------------------------------------------+ 

你可以用下面的方法将它们组装形式:

public byte[] transceiveCommand(NfcF tag, byte commandCode, byte[] idM, byte[] param) { 
    if (idM == null) { 
     // use system IDm 
     idM = tag.getTag().getId(); 
    } 
    if (idM.length != 8) { 
     idM = Arrays.copyOf(idM, 8); 
    } 

    if (param == null) { 
     param = new byte[0]; 
    } 

    byte[] cmd = new byte[1 + 1 + idM.length + param.length]; 

    // LEN: fill placeholder 
    cmd[0] = (byte)(cmd.length & 0x0FF); 

    // CMD: fill placeholder 
    cmd[1] = commandCode; 

    // IDm: fill placeholder 
    System.arraycopy(idM, 0, cmd, 2, idM.length); 

    // PARAM: fill placeholder 
    System.arraycopy(param, 0, cmd, 2 + idM.length, param.length); 

    try { 
     byte[] resp = tag.transceive(cmd); 
     return resp; 
    } catch (TagLostException e) { 
     // WARN: tag-loss cannot be distinguished from unknown/unexpected command errors 
    } 

    return null; 
} 

例如,应该在大多数标签成功的命令是请求系统代码命令(0x0E):

nfcf.connect(); 
byte[] resp = transceiveCommand(nfcf, (byte)0x0C, null, null); 
nfcf.close();