我正在尝试使用sector_select向指定扇区读取和写入/写入,但是当我通过MifareUltralight.transceive()
发送命令的第二部分时,请获得TagLostException
。我如何选择和操纵扇区?
我正在使用Android Nexus 6(6.0.1)将命令发送到NXP NTAG(NT3H1201)的数据。我能够使用cerceceive(通过NfcA
和MifareUltralight
)使用get_version命令(60h)。
我使用的方法选择一个扇区:
public void selectSector(byte sector, MifareUltralight mifareUltralight) throws IOException {
if (mifareUltralight.isConnected()) {
mifareUltralight.close();
}
// SECTOR_SELECT command (see nxp p. 46)
byte[] sectorSelectCmdPacket1 = new byte[2];
byte[] sectorSelectCmdPacket2 = new byte[4];
sectorSelectCmdPacket1[0] = (byte) 0xc2; // Sector select command
sectorSelectCmdPacket1[1] = (byte) 0xff;
sectorSelectCmdPacket2[0] = sector; // Memory sector to be selected; 1 for I2C 2k version
sectorSelectCmdPacket2[1] = (byte) 0x00;
sectorSelectCmdPacket2[2] = (byte) 0x00;
sectorSelectCmdPacket2[3] = (byte) 0x00;
mifareUltralight.connect();
try {
// ACK = 0A
byte[] sectorSelectResp1 = mifareUltralight.transceive(sectorSelectCmdPacket1);
Log.w(TAG, bytesToHex(sectorSelectResp1));
} catch (IOException e) {
Log.w(TAG, "selectSector: there was an exception while sending first sector select command");
e.printStackTrace();
}
try {
mifareUltralight.transceive(sectorSelectCmdPacket2);
Log.w(TAG, "Second sector select command sent");
} catch (IOException e) {
Log.w(TAG, "selectSector: there was an exception while sending second sector select command");
e.printStackTrace();
}
mifareUltralight.close();
}
当我调用SelectSector方法时,第一个cercective完成但第二个未完成,导致错误
android.nfc.taglostexception:丢失了标签。
我如何选择和操纵扇区而不获得TagLostException
?
sector_Select命令的第二阶段导致TagLostException
是正常的。这发生在许多Android设备上,这是由sector_Select命令的第二阶段所造成的(被动ack)。收到该特定命令的例外后,您可以安全地与标签进行通信。只有当您收到一个命令中的TagLostException
时,您期望有明确的ACK/响应数据,通信出现了问题。
还要注意,选择扇区后应该关闭连接,因为这将重置某些Android设备上的标签。因此,当您以后重新连接标签时,可能不再选择该扇区。
典型的扇区选择方法看起来像这样:
public boolean selectSector(int sector) throws IOException {
byte[] cmd_sel1 = { (byte)0xC2, (byte)0xFF };
byte[] cmd_sel2 = { (byte)sector, (byte)0x00, (byte)0x00, (byte)0x00 };
byte[] result1 = transceive(cmd_sel1);
if (result1 == null) {
throw new TagLostException();
} else if ((result1.length == 1) && ((result1[0] & 0x00A) == 0x000)) {
// NACK response according to DigitalProtocol
return false;
} else {
try {
byte[] result2 = transceive(cmd_sel2);
if (result2 == null) {
throw new TagLostException();
} else if ((result2.length == 1) && ((result2[0] & 0x00A) == 0x000)) {
// NACK response according to DigitalProtocol
return false;
} else {
return true;
}
} catch (Exception e) {
// passive ACK
return true;
}
}
}