Android NFC intentions do not start my activity

I am trying to write a simple application for interacting with NFC tags, but I can not get my phone to do anything other than launch the default NFC tag. I just want to be able to intercept any tag that I scan, determine if it has some data on it, and take appropriate action.

Currently 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 I scan an NFC tag, I never see an activity start. Am I missing something? I tried to place an intent filter inside the BroadcastReceiver and no luck and ...

+8
android android-intent nfc
source share
4 answers

You cannot run your application with all the NFC tags that you are viewing. Android will determine which application is most appropriate based on how specific the intent filter is. However, if your application runs in the foreground, you can use the NFC foreground dispatch to catch all the intentions of NFC.

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 the NFC tag as follows:

 Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); 
+21
source share

SDK docs show this as a basic example.

 <intent-filter> <action android:name="android.nfc.action.NDEF_DISCOVERED"/> <category android:name="android.intent.category.DEFAULT"/> <data android:mimeType="text/plain" /> </intent-filter> 
+6
source share

It is expected that tags will be defined in NDEF format. Thus, your program will be launched only if the read tags are in NDEF format.

You can try more general intent filters, such as TAG_DISCOVERED or TECH_DISCOVERED.

+1
source share

Android automatically removes the most relevant application for processing the scanned NFC tag. You should be more specific in your intent-filter , i.e. Listen only to TEXT tags, URL tags or CONTACT tags. This can be done by specifying a filter, using, for example, <data android:mimeType="text/plain" /> for TEXT tags. Otherwise, the default NFC-Tag application will be launched.

0
source share

All Articles