【发布时间】:2014-05-16 12:56:42
【问题描述】:
我正在尝试以下方法:
- 向 NFC 标签写入一条消息,其中包含对我的应用程序的引用以及我可以用来识别标签的短字符串。
- 阅读该消息。
为了在开始时加快测试速度,我使用了应用程序 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;
}
【问题讨论】:
-
"我已经测试了几种方法,但都没有奏效。": 什么没有奏效?标签没有写入吗?您的应用程序无法启动吗?您的应用程序是否启动但没有收到文本?你得到什么错误?
标签: android text nfc launch ndef