I am developing an app that will use NFC tags for identification. All examples I find however, are about starting an app when a certain card is read. I tried looking for an exam
I found part of the answer here: NFC broadcastreceiver problem
That solution doesn't provide a complete working example, so I tried a little extra. To help future visitors, I'll post my solution. It is a NfcActivity
which subclasses Activity
, if you subclass this NfcActivity
, all you have to do is implement its NfcRead
method, and you're good to go:
public abstract class NfcActivity extends Activity {
// NFC handling stuff
PendingIntent pendingIntent;
NfcAdapter nfcAdapter;
@Override
public void onResume() {
super.onResume();
pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
nfcAdapter = NfcAdapter.getDefaultAdapter(this);
nfcAdapter.enableForegroundDispatch(this, pendingIntent, null, null);
}
@Override
protected void onPause() {
super.onPause();
nfcAdapter.disableForegroundDispatch(this);
}
// does nothing, has to be overridden in child classes
public abstract void NfcRead(Intent intent);
@Override
public void onNewIntent(Intent intent) {
String action = intent.getAction();
if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)) {
NfcRead(intent);
}
}
}