[英]Reading a message stored on NDEF tag. Android
我試圖找到一個工作示例,說明如何讀取存儲在應用程序活動活動中的 NDEF 標簽上的消息。 到目前為止,我擁有的最好的是這樣的代碼:
public class Activity1_3_1_1 extends AppCompatActivity {
private Button done;
NfcAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity1_3_1_1);
done = findViewById(R.id.button5);
done.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
switchActivityTo1();
}
});
}
private void switchActivityTo1() {
Intent switchActivityIntent = new Intent(this, MainActivity.class);
startActivity(switchActivityIntent);
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
adapter = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); // get the detected tag
Parcelable[] msgs =
intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
NdefRecord firstRecord = ((NdefMessage) msgs[0]).getRecords()[0];
byte[] payload = firstRecord.getPayload();
int payloadLength = payload.length;
int langLength = payload[0];
int textLength = payloadLength - langLength - 1;
byte[] text = new byte[textLength];
System.arraycopy(payload, 1 + langLength, text, 0, textLength);
Toast.makeText(getApplicationContext(), new String(text), Toast.LENGTH_LONG).show();//display the response on screen
}
}
}
和清單文件:
...
<uses-permission android:name="android.permission.NFC"/>
<uses-feature android:name="android.hardware.nfc"/>
...
<activity
android:name=".Activity1_3_1_1"
android:exported="true"
android:alwaysRetainTaskState="true"
android:launchMode="singleTask">
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
問題是 NFC 服務正在啟動,而不是應用程序的 onNewIntent() 方法。 對我來說,弄清楚清單文件搞砸了是個問題(因為解決方案之一是修改清單文件以使 NFC 服務無法啟動),或者是活動代碼本身內部的問題。 或者,也許,兩者兼而有之。
等待您的解決方案。
因此,Android 中 NFC 的正常模式是:-
1)當您的應用程序未運行時,您希望它在某種類型的 NFC 標簽呈現給設備時啟動,然后您將您的intent-filters
放入清單中。 然后您的應用程序將啟動並傳遞您需要在onCreate
方法中使用getIntent()
處理的Intent
2a)您的應用程序已經在前台運行,然后您使用enableForegroundDispatch
,給它一個待處理的 Intent 您想要通知的內容,然后在您的應用程序重新啟動(暫停和恢復)以接收 Intent 時在onNewIntent
中進行處理。
onNewIntent
不會被任何清單條目調用。
或者
2b)您的應用程序已經在前台運行,然后您使用enableReaderMode
,它是enableForegroundDispatch
的更好替代品,然后您在onTagDiscovered
中處理標簽,它位於單獨的線程中。
如何處理通過模式 1 和 2a 接收到的Intent
是相同的,只是需要從與觸發 Intent 的方法相匹配的代碼中的正確路徑調用它們,即在onCreate
或onNewIntent
查看空 NFC 標簽讀寫 Android 應用程序。 掃描空標簽時移動自己的消息返回但應用程序不起作用? 有關如何使用 Manifest 和enableForeGroundDispatch
的示例
還有很多在 Stackoverflow 上使用enableReaderMode
的例子。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.