When an Android device receives an NDEF Message (for example by reading an NFC tag) it processes it through a dispatch mechanism to determine an activity to launch.
Use NdefMessage(byte[])
to construct an NDEF Message from binary data, or NdefMessage(NdefRecord[])
to construct from one or more NdefRecords.
The type of the first record in the message has special importance for message dispatch, so design this record carefully.
Get the NDEF Records inside this NDEF Message.
An NdefMessage always has one or more NDEF Records: so the following code to retrieve the first record is always safe (no need to check for null or array length >= 1):
NdefRecord firstRecord = ndefMessage.getRecords()[0];
Returns:
array of one or more NDEF records.
A one-tap approach is not possible using Beam on two Android devices
(note that with other devices, particularly if one is Android and one
is a dedicated NFC reader or a device where you can control the NFC
functionality on a low level or a device that emulates an NFC tag).
However, a two-tap approach is possible between two Android devices with only little modifications to your existing scenario.
You simply need to add a foreground dispatch that intercepts your incoming NDEF message and consequently prevents Android from restarting your activity:
@Override
public void onResume() {
super.onResume();
NfcAdapter adapter = NfcAdapter.getDefaultAdapter(this);
PendingIntent pi = PendingIntent.getActivity(
this,
0,
new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),
0);
adapter.enableForegroundDispatch(this, pi, null, null);
}