Я получил все успешно, прочитав сообщение NDEF из тега NFC.И после того, как я прочитал, я перемещаю телефон, и он может снова прочитать тег.
Я использую onNewIntent и foregroundDispatch для обработки сообщения.
Проблема заключается в следующем: я хочу прочитатьодин и тот же тег 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?
}
Так как же я могу снова прочитать тег?