-1

Is it possible to send a NDEF message without input from the user?

I would like to use NFC in the following scenario: The user taps Device on NFC reader. NFC reader receives message as response.

Essentially I want the device to operate as a Tag i.e. without input from the user.

I know KitKat 4.4 Supports HCE (Host card emulation) although i'd like a solution with greater device support such as NDEF messages.

John
  • 754
  • 1
  • 10
  • 26

1 Answers1

1

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);
}
SID --- Choke_de_Code
  • 1,131
  • 1
  • 16
  • 41