通过从NFC标签读取NDEF消息,我一切都成功了。读完之后,我移动手机,它便可以再次读取标签。
我正在使用onNewIntent和outlookDispatch处理消息。
问题是: 我想两次读取相同的NFC标签(出于安全原因),而无需移动电话(无需再次触摸标签)。因此,我想一次阅读两次。
我尝试查看生命周期,但似乎如果您不移动手机,它将不会再次发出新的意图。
private NfcAdapter nfc = null;
private boolean inReadMode = false;
private boolean isNFC_support = false;
private PendingIntent mPendingIntent;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ignore the unrelevent part of layout
isNFC_support = true;
nfc = NfcAdapter.getDefaultAdapter(this);
if(nfc == null) {
Toast.makeText(this, "Not support NFC device.", Toast.LENGTH_LONG).show();
isNFC_support = false;
}
if(!nfc.isEnabled()) {
Toast.makeText(this, "Please go the setting and enable NFC first.", Toast.LENGTH_LONG).show();
isNFC_support = false;
}
if (isNFC_support == true) {
mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
}
}
@Override
protected void onNewIntent(Intent intent) {
Log.i("NFC", "---- onNewIntent called ---- ");
if (this.inReadMode && NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
Log.i("NFC", "---- onNewIntent called ---- AND read nfc success!");
try {
readFromTag(intent);
} catch (Exception e) {
Log.e("NFC", "nfc cmac validate: ", e);
}
}
}
@Override
public void onResume() {
super.onResume();
Log.i("NFC", "---- onResume called ---- ");
nfc.enableForegroundDispatch(this, mPendingIntent, null, null);
}
@Override
public void onPause() {
Log.i("NFC", "---- onPause called ---- ");
if (nfc != null) {
nfc.disableForegroundDispatch(this);
}
if (isFinishing()) {
cleanupReadingFromTag();
}
super.onPause();
}
private void readFromTag(Intent intent) throws RuntimeException, NoSuchAlgorithmException, IOException {
Parcelable[] msgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
// code I handle the message as I get. Not important for read twice I think?
}
那么我该如何再次读取标签?
答案 0 :(得分:1)
仅在检测到 NFC标签时调度NFC意图。如果标签包含NDEF消息,则会自动处理该消息并与您的应用程序共享此消息(NfcAdapter.EXTRA_NDEF_MESSAGES
)。
如果您想在以后再次读取标签(并设法使NFC标签始终保持连接状态),则需要直接与标签通信。您可以通过标签句柄对象执行此操作。检测到标签后,该对象(类Tag
)也会传递到您的应用程序(作为NFC意图的额外意图):
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
在连接标签后,您可以随时使用该对象来启动与标签的通信。例如。要重新读取标签上的当前NDEF消息,可以使用:
Ndef ndef = Ndef.get(tag);
if (ndef != null) {
try {
ndef.connect();
NdefMessage msg = ndef.getNdefMessage();
// do something with the NDEF message
} catch (IOException e) {
} finally {
try {
ndef.close();
} catch (Exception e) {}
}
}