在Android上读取NFC-F卡时出现TagLostException

在Android上读取NFC-F卡时出现TagLostException,android,tags,nfc,ioexception,contactless-smartcard,Android,Tags,Nfc,Ioexception,Contactless Smartcard,我正在开发一个Android应用程序,它需要读取NFC卡(卡技术是NFC-F)。在那里,我总是遇到以下例外情况: android.nfc.TagLostException:标记丢失 这是我的密码: private void handleIntent(Intent intent) { String action = intent.getAction(); if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) { } e

我正在开发一个Android应用程序,它需要读取NFC卡(卡技术是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());
            }
        }
    }
}

有人能帮我解决这个问题吗?

您收到一个
TagLostException
,因为您向标记发送了一个无效命令。由于NFC-F标签在接收到无效命令时保持沉默,Android无法区分实际通信中断或对不支持/无效命令的负面响应,并在这两种情况下抛出
TagLostException

有效的FeliCa(NFC-F)命令具有以下形式

+----------+----------+------------------+-----------------------------------------------+ | LEN | COMMAND | IDm | PARAMETER | | (1 byte) | (1 byte) | (8 bytes) | (N bytes) | +----------+----------+------------------+-----------------------------------------------+ 例如,在大多数标记上应该成功的命令是请求系统代码命令(0x0E):


改进的格式
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;
}
nfcf.connect();
byte[] resp = transceiveCommand(nfcf, (byte)0x0C, null, null);
nfcf.close();