我正在开发一个Android应用程序,以读取和写入不同的NFC标签。我在使用特定标签iCODE SLI X和iCODE SLI S时遇到了问题。在标签上写入信息后,我无法执行其他任何操作,看起来NFC停止正常工作,因为如果我重新启动它,它将实际读取标签。如果我使用其他标签类型(例如MIFARE Classic 1K),则不会发生这种情况。 Android版本是6.0。

另一方面,如果我在具有Android 6.1或7.0(完全相同的代码)的另一台设备上尝试该应用程序,则iCODE SLI X和iCODE SLIS可以正常工作,但不能使用MIFARE Classic 1K。

除了尝试不同的代码示例外,我还在这些设备上尝试了2种应用程序。在“NFC工具”上,您可以看到与我的应用程序完全相同的问题。恩智浦的“TagWriter”是唯一一种对所有类型的标签都具有吸引力的应用程序。

这是我用来在标签上写信息的代码:

@Override
protected void onNewIntent(Intent intent) {

    if (mNfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        if (tag != null) {
            try {
                Ndef ndef = Ndef.get(tag);

                NdefRecord text1 = new NdefRecord(NdefRecord.TNF_WELL_KNOWN,
                        youstring1.getBytes(Charset.forName("US-ASCII")),
                        null,
                        youstring1.getBytes());

                NdefRecord text2 = new NdefRecord(NdefRecord.TNF_WELL_KNOWN,
                        youstring2.getBytes(Charset.forName("US-ASCII")),
                        null,
                        youstring2.getBytes());

                NdefRecord[] records = {text1, text2};

                NdefMessage message = new NdefMessage(records);


                if (ndef != null) {
                    NdefMessage ndefMesg = ndef.getCachedNdefMessage();
                    if (ndefMesg != null) {
                        ndef.connect();
                        ndef.writeNdefMessage(message);
                        ndef.close();
                    }
                } else {
                    NdefFormatable ndefFormatable = NdefFormatable.get(tag);
                    if (ndefFormatable != null) {
                        // initialize tag with new NDEF message
                        try {
                            ndefFormatable.connect();
                            ndefFormatable.format(message);
                            ndefFormatable.close();
                        } finally {
                            try {
                                //ndefFormatable.close();
                            } catch (Exception e) {
                            }
                        }
                    }
                }
            }catch (FormatException |IOException ue){}
        }
    }
}

我不明白我可能做错了什么...

最佳答案

我设法了解应用程序出了什么问题,所以我自己发布了答案。这是东西:

当我尝试在标签上写信息时,我首先检查标签是否格式化为在标签上使用“Ndef”技术,否则,我使用“NdefFormatable”对标签进行格式化。

奇怪的是,某些设备中的某个标签支持“NdefFormatable”,而某些设备则不支持。 (不确定其是否与NFC本身或操作系统版本有关)。在尝试使用“NdefFormatable”后,这导致NFC行为异常或根本无法工作。

我现在正在做的是建立此函数,该函数提供可在标签上使用的技术。取决于它,我使用“NdefFormatable”或“NfcV”(用于iCODE标签)在标签上进行读取或写入。

09-27 13:01
查看更多