Question

Hey Guys im trying to programm my own NFC-reader.
Ive done some tutorials but they are always for apps which start when a NFC-Tag is detected.
I want my app to just detect them and change a textview or something.

So i've tried to setup a Broadcastfilter:

    IntentFilter filter = new IntentFilter();
    filter.addAction(NfcAdapter.ACTION_NDEF_DISCOVERED);
    filter.addAction(NfcAdapter.ACTION_TAG_DISCOVERED);
    filter.addAction(NfcAdapter.ACTION_TECH_DISCOVERED);

    getApplicationContext().registerReceiver(mReceiver, filter);

But when im holding the NCF tag next to my mobile "mReceiver" doesnt do anything.

What do i do wrong? Can anybody help me pls?

Was it helpful?

Solution

First setup your NFC-Adapter in onCreate() by

NFCAdapter adapter = NfcAdapter.getDefaultAdapter(this);

Furthermore you have to enable the foreground dispatch system (best in onResume()) via

final Intent intent = new Intent(this, activity.getClass());
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
final PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
IntentFilter[] filters = new IntentFilter[1];
// add here all tag types you want to discover
String[][] techList = new String[][]{};
filters[0] = new IntentFilter();
filters[0].addAction(NfcAdapter.ACTION_NDEF_DISCOVERED);
filters[0].addCategory(Intent.CATEGORY_DEFAULT);
// add type of tag data you want to have - here ndef -> plain text
filters[0].addDataType("text/plain");
// now set the foregorund dispatch (disable it again in onStop())
adapter.enableForegroundDispatch(this, pendingIntent, filters, techList);

Now you can catch intents to your activity on newIntent() for your tag intents and process the data.

Hope that helps!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top