[英]Write An NDEF Message To A Tag Inside Runnable
我最近開始在Android上開發,並開始使用帶有NDEF消息的NFC標簽的項目。 我設法創建了一個簡單的應用程序,它將從text / plain NDEF記錄中讀取並將數據寫入屏幕。
現在我正致力於將NDEF消息寫入標簽。 我好像有它工作,但想知道是否最好在主UI線程以外的線程上編寫標簽?
在最近開始學習之后,我被教導在主線程中執行(可能)長時間運行的任務是禁止的,並且認為寫入標簽會如此。 但是,將代碼寫入Runnable()中的標記似乎會導致寫入失敗。 所以,我的問題是。 我錯誤地認為寫入標簽應該是從主線程完成的嗎? 或者我錯了使用Runnable? 並且如果之前已經回答道歉,我嘗試谷歌搜索,但在這個主題上找不到多少。
我已經包含了我的示例代碼:
按鈕處理程序:
public void writeButton(View view)
{
//Some validation
createMessageToWrite();
}
創建消息:
public void createMessageToWrite()
{
EditText messageBox = (EditText)findViewById(R.id.toWrite);
String toWrite = messageBox.getText().toString();
if(toWrite.length() == 0)
toWrite = "This is some text from My writer";
NdefRecord textRecord = NdefRecord.createMime("text/plain", toWrite.getBytes());
NdefRecord aar = NdefRecord.createApplicationRecord(getPackageName());
NdefMessage message = new NdefMessage(new NdefRecord[]{textRecord, aar});
messageToWrite=message;
Toast.makeText(getApplicationContext(), "Message made", Toast.LENGTH_SHORT).show();
write();
}
最后,我的代碼寫入標簽:
public void write()
{
Toast.makeText(getApplicationContext(),"Starting write. Touch tag",Toast.LENGTH_SHORT).show();
sleep(3000);
// Runnable r = new Runnable()
//{
// @Override
// public void run()
// {
Toast.makeText(getApplicationContext(),"Starting runnable. Touch tag",Toast.LENGTH_SHORT).show();
sleep(3000);
if(messageToWrite == null)
{
Toast.makeText(getApplicationContext(),"Message is null",Toast.LENGTH_SHORT).show();
return;
}
Toast.makeText(getApplicationContext(), "Trying", Toast.LENGTH_SHORT).show();
sleep(3000);
try
{
if(theTag != null)
{
theTag.connect();//The tag is a global var set in onCreate() or onNewIntent()
theTag.writeNdefMessage(messageToWrite);
theTag.close();
}
else
{
Toast.makeText(getApplicationContext(), "tag is null", Toast.LENGTH_SHORT).show();
}
}
catch (IOException e)
{
e.printStackTrace();
Toast.makeText(getApplicationContext(), "IOException", Toast.LENGTH_LONG).show();
}
catch (FormatException e)
{
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Format", Toast.LENGTH_LONG).show();
}
Toast.makeText(getApplicationContext(),"Written",Toast.LENGTH_SHORT).show();
}
// };
// Thread t = new Thread(r);
// t.start();
// }
發布的代碼有效,但取消注釋Runnable()的東西會導致應用程序崩潰。 不幸的是,我正在處理的系統沒有設置為允許從設備進行USB調試,而我沒有安裝驅動程序的權限。 所以,在設置之前,我必須滿足於“應用已經停止工作”的消息......
非常感謝任何和所有的幫助
編輯:語法
首先,在不知道你得到什么異常的情況下,我會假設崩潰/異常不是由在單獨的線程中執行寫操作而是通過從非UI線程顯示Toast
引起的。
必須始終從UI線程顯示Toast
s。 您可以通過包裝Toast.makeText(...).show()
調用來解決此問題,如下所示:
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(YourActivityClass.this, yourMessage, Toast.LENGTH_SHORT).show();
}
});
其次,優良作法是在單獨的線程中訪問NFC標簽(或者通常用於執行IO操作)。
第三,用戶與NFC標簽的交互通常是非常短的動作,並且用戶通常僅在實際的讀取,寫入等操作期間敲擊標簽。 因此,保存Tag
句柄並在稍后用戶輸入(按下按鈕)時調用寫入操作通常是一個非常糟糕的想法(盡管可能存在一些罕見的例外)。
更好的方法是存儲要寫入的NDEF消息,將應用程序設置為某種“寫入模式”狀態,並提示用戶點擊標記。 然后,在標記檢測時,啟動寫入線程並讓它寫入先前保存的消息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.