[英]Write and read application record to NFC tag on Android
我正在尝试以下方法:
为了在一开始就加快测试速度,我使用了应用Tagwriter( https://play.google.com/store/apps/details?id=com.nxp.nfc.tagwriter&hl=de )使用我的需求:在下一个窗口中“创建纯文本”和“添加启动应用程序”。
接触标签后,我的手机将启动我的应用程序,它甚至会正确读取识别字符串。 但是我也希望它从我自己的应用程序中编写标记,而不是引用另一个。
我已经测试了几种方法,但没有一种有效。 我的应用程序根本没有启动,或者无法读取字符串。 谁能帮我?
public static boolean writeTag(String textToWrite, Tag tag)
{
Miscellaneous.logEvent("i", "NFC", "Attempting to write tag...", 2);
String packageName = Miscellaneous.getAnyContext().getPackageName();
NdefRecord appRecord = NdefRecord.createApplicationRecord(packageName);
// Record with actual data we care about
NdefRecord textRecord = new NdefRecord(NdefRecord.TNF_MIME_MEDIA,
new String("application/" + packageName)
.getBytes(Charset.forName("US-ASCII")),
null, textToWrite.getBytes());
// Complete NDEF message with both records
NdefMessage completeMessageToWrite = new NdefMessage(new NdefRecord[] {textRecord, appRecord});
int size = completeMessageToWrite.toByteArray().length;
try
{
Ndef ndef = Ndef.get(tag);
if (ndef != null)
{
ndef.connect();
if (ndef.isWritable() && ndef.getMaxSize() > size)
{
ndef.writeNdefMessage(completeMessageToWrite);
Miscellaneous.logEvent("i", "NFC", "Done writing tag.", 2);
return true;
}
}
else
{
NdefFormatable format = NdefFormatable.get(tag);
if (format != null)
{
try
{
format.connect();
format.format(completeMessageToWrite);
Miscellaneous.logEvent("i", "NFC", "Done writing tag.", 2);
return true;
}
catch(IOException e)
{
Miscellaneous.logEvent("e", "NFC", "Error writing tag: " + Log.getStackTraceString(e), 2);
}
}
}
}
catch(Exception e)
{
Miscellaneous.logEvent("e", "NFC", "Error writing tag: " + Log.getStackTraceString(e), 2);
}
return false;
}
抱歉,本来可以更详细一些。 看来我自己解决了我的问题。 我一直在从该网站上获取一些示例代码,并从该网站上获取一些代码...这就是为什么我必须首先清理一下然后再回答这里的原因。 在此过程中,我发现了错误。 现在,写入功能如下所示:
public static boolean writeTag(String textToWrite, Tag tag)
{
Miscellaneous.logEvent("i", "NFC", "Attempting to write tag...", 2);
String packageName = Miscellaneous.getAnyContext().getPackageName();
NdefRecord appRecord = NdefRecord.createApplicationRecord(packageName);
// Record with actual data we care about
byte[] textBytes = textToWrite.getBytes();
byte[] textPayload = new byte[textBytes.length + 3];
textPayload[0] = 0x02; // 0x02 = UTF8
textPayload[1] = 'e'; // Language = en
textPayload[2] = 'n';
System.arraycopy(textBytes, 0, textPayload, 3, textBytes.length);
NdefRecord textRecord = new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], textPayload);
// Complete NDEF message with both records
NdefMessage completeMessageToWrite = new NdefMessage(new NdefRecord[] {textRecord, appRecord});
[...]
}
看来“ apprecord”很好,但文本记录却不好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.