我正在尝试创建一个样本来读取和写入NFC标签的数据。 我正在使用AAR和其他时间戳信息将数据写入NFC标签,如下所示:
Message message = new Message();
AndroidApplicationRecord aar = new AndroidApplicationRecord(AAR);
message.add(aar);
TextRecord textRecord = new TextRecord(String.valueOf(currServiceDate));
message.add(textRecord);
现在,如果我退出应用并扫描NFC标签,我的活动会因AAR条目而启动,但我无法读取NDEF消息。要读取NDEF消息,我必须再次扫描NFC标签,然后才能查看标签上存储的数据。
我的onResume代码:
@Override
protected void onResume() {
Log.d(TAG, "onResume");
super.onResume();
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
Parcelable[] rawMsgs = getIntent().getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
Log.e(TAG , "detect message");
}
enableForegroundMode();
}
public void enableForegroundMode() {
if (nfcAdapter != null) {
IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED); // filter for all
IntentFilter ndefDetected = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED); // filter for all
IntentFilter[] writeTagFilters = new IntentFilter[] {tagDetected, ndefDetected};
nfcAdapter.enableForegroundDispatch(this, nfcPendingIntent, writeTagFilters, null);
} else {
Toast.makeText(this, "NFC is not supported on this device", Toast.LENGTH_LONG).show();
}
}
onCreate 中的代码:
public void readTagIntent() {
Intent intent = getIntent();
Log.i(TAG + " EXTRA_TAG called ", currentTagId+" "+intent.getAction());
if(intent != null) {
if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
if (intent.hasExtra(NfcAdapter.EXTRA_TAG)) {
currentTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
currentTagId = SenseMeUtils.toHexString(currentTag.getId());
Log.i(TAG + " EXTRA_TAG readTagIntent ", currentTagId+"");
}
}
}
}