Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android NFC Intents are not starting my activity

I am trying to write a simple application to interact with NFC tags, but I cant seem to get my phone to do anything but trigger the default NFC tag app. I really just want to be able to intercept any tag I scan, determine if it has some data on it, and take action accordingly.

Right now my manifest file looks like

<uses-sdk android:minSdkVersion="10" />
<uses-feature android:name="android.hardware.nfc" android:required="true"/>
<uses-permission android:name="android.permission.NFC"/>

<application 
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >
    <activity
        android:name=".NfcActivity"
        android:label="@string/app_name">
        <intent-filter>
           <action android:name="android.intent.action.MAIN"/>
           <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
        <intent-filter>
            <action android:name="android.nfc.action.NDEF_DISCOVERED"/>
        </intent-filter>
    </activity>
</application>

However when scanning an NFC tag, I never see the activity start. Am I missing something here? I tried placing the intent filter inside a BroadcastReceiver and had no luck either...

like image 384
FlyingStreudel Avatar asked Jun 17 '12 21:06

FlyingStreudel


1 Answers

You cannot have your app started by all NFC tags you scan. Android will determine what the most suitable app is based on how specific the intent filter is. However, if your app is running in the foreground, you can use NFC foreground dispatch to catch all NFC intents.

In onCreate() add:

mAdapter = NfcAdapter.getDefaultAdapter(this);
PendingIntent pendingIntent = PendingIntent.getActivity(
  this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

In onResume() add:

mAdapter.enableForegroundDispatch(this, pendingIntent, null, null);

In onPause() add:

mAdapter.disableForegroundDispatch(this);

In onNewIntent you can get at the NFC tag like this:

Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
like image 113
NFC guy Avatar answered Sep 20 '22 00:09

NFC guy