Android Tutorial Reading NDEF data from NFC tags

Using the NFC library you can read NFC tags formatted in NDEF form (NFC Data Exchange Format).
You can read more information about the internal process here: NFC Basics | Android Developers

This library requires Android version 2.3.3 or above (API level 10 or above).

Whenever an NDEF tag is read, Android sends an intent with the extracted data. You should declare that your activity wants to handle such intents.
This is done by adding "intent filters" with the manifest editor.

There are two types of data that you can handle: text data and Uri data.

When your activity receives an Intent, the activity is first created. If the activity is currently running then it will be paused and created again.

You can use code similar to the following code to test whether the starting intent is actually an Ndef intent and then extract the records (usually a single record) from the intent:
B4X:
Sub Process_Globals
   Dim NFC As NFC
End Sub

Sub Activity_Resume
   If NFC.IsNdefIntent(Activity.GetStartingIntent) Then
      Dim records As List
      records = NFC.GetNdefRecords(Activity.GetStartingIntent)
      For i = 0 To records.Size - 1
         Dim r As NdefRecord
         r = records.Get(i)
         Log(r.GetAsTextType)
      Next
   End If
End Sub

Text data
Tags with text data include a MIME field that helps the OS decide which application should handle the intent.
For example if you want to handle messages with the "text/plain" mime (with the main activity) then you should add the following code in the manifest editor:
B4X:
AddActivityText(main, <intent-filter>
    <action android:name="android.nfc.action.NDEF_DISCOVERED"/>
    <category android:name="android.intent.category.DEFAULT"/>
    <data android:mimeType="text/plain" />
</intent-filter>)
Note that you can add any number of intent filters.

Call NdefRecord.GetAsTextType to convert the payload to a string.


Uri data
The intent filter of Uri tags should look like:
B4X:
AddActivityText(main, <intent-filter>
    <action android:name="android.nfc.action.NDEF_DISCOVERED" />
    <category android:name="android.intent.category.DEFAULT" />
    <data android:scheme="http"
        android:host="www.b4x.com" />
</intent-filter>)
The above example will handle any Uri that points to a page starting with ht*p://www.b4x.com.

Call NdefRecord.GetAsUriType to convert the payload to the Uri.

Testing NFC tags
I recommend you to use an application such as NFC TagWriter by NXP.
It allows you to store data formatted as Ndef on many types of tags.

NFC TagInfo is also useful to find the stored data and the mime type.

The library is available here: http://www.b4x.com/forum/additional-libraries-official-updates/14933-nfc-library.html
 

bluedude

Well-Known Member
Licensed User
Longtime User
Using NFC payload strips the http:// and www and adds a strange first character

Hi,

I have used the NFC library a lot but I notice now that using the payload method does weird stuff to my URLs and adds a character in front of it.

I does this:
fcData=byteCon.StringFromBytes (r.GetPayload ,"UTF8")

I use this method to first check if it is an URL. However, because it strips the http and www I'm not 100% sure anymore if it is an URL. Checking on forward slash wouldn't help. The url's are stripped like this:
outube.com/watch?v=8f7wj_RcqYk

Cannot show you the weird character here, it cannot be pasted. It says SOH.

After checking for payload I do:

nfcData=r.GetAsUriType

There is no 100% way to check if it is text or an URL because GetAsTextType also returns part of the URL.

These are my intent filters:

AddActivityText(main, <intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="http" />
</intent-filter>)
AddActivityText(main, <intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="text/plain" />
</intent-filter>)

Not checking on hostname because every URL needs to be recognized.
 

Smee

Well-Known Member
Licensed User
Longtime User
i am getting an artefact each time i swipe the tag. The artefact is the screen being redrawn i think. i guess because the activity is being recreated each time. How can i avoid this?

All i have is 2 labels on the activity and they are updated each time the tag is touched.
 

Smee

Well-Known Member
Licensed User
Longtime User
Can you post a screenshot?

Are you building the layout in Activity_Resume (this is not the correct place)?

No, It happens too quick to capture

No.

It is just a test project so i can understand how everything works. this is the code

B4X:
Sub Activity_Create(FirstTime As Boolean)
   'Do not forget to load the layout file created with the visual designer. For example:
      Activity.LoadLayout("main")
End Sub

Sub Activity_Resume
   If Activity.GetStartingIntent=LastIntent Then Return
   If NFC.IsNdefIntent(Activity.GetStartingIntent) Then
      GetNFCRecord
   End If
   LastIntent=Activity.GetStartingIntent
End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub

Sub GetNFCRecord
   Dim PointsInc As Int
   
   If EventType="Raffle" Then
      PointsInc=5
      lblEvent.Text=EventType
      EventType="Bar-B-Que"
   Else
      PointsInc=1
      lblEvent.Text=EventType
      EventType="Raffle"
   End If

        Dim records As List
        records = NFC.GetNdefRecords(Activity.GetStartingIntent)
'        For i = 0 To records.Size - 1
            Dim r As NdefRecord
         r = records.Get(0)
         Log(r.GetAsTextType)
         lblName.Text=r.GetAsTextType
         Points=Points+PointsInc
         lblPoints.Text=Points
'        Next
lblPoints.Visible=True
lblName.Visible=True
lblEvent.Visible=True

End Sub
 

Peter Simpson

Expert
Licensed User
Longtime User
NFC library works great, but I need some help...

Thank for this library, it works great :)

I was wondering if anybody knows how I can actually handles NFC tags in the actual app/activity that is open at the time of scanning the NFC tag. I need to process the data in the actual app that I'm developing and not in a popup background activity.

Any help would be greatly appreciated.

P.S. I know that I can create 2 apps for this, but that defeats the object. I know that I can use this library to create the background task that reads tags and write the information to a file that the open activity can then read. But there has to be a better way to handle it.

Thank you :sign0163:
 

Peter Simpson

Expert
Licensed User
Longtime User
I think that

Activity_Resume should be called even if the activity is already visible.

Thank you for that Erel, but I think that you have my question wrong.

I can already resume the task in the first application. I would like to find a way handle reading NFC tags in the main app that is open(this is an app I've been asked to look into developing). My client is looking for the same app to handle reading NFC internally, not externally. I know I can do it with 2 app(the first using your simple but effective NFC code :sign0098: ) but the client would prefer to only install one app on their tablets.

Thank you again for your
 

Peter Simpson

Expert
Licensed User
Longtime User
Thank you. Foreground Dispatch System

Hello,
Thank you for your response, it's seriously appreciated.

From what I've been reading, the only way to make sure that the currently active application intercepts and handles the NFD action is by using Foreground Dispatch System. You actually already responded to somebody else with the same issue, you told them that a library had to be written, that's why I'm after a Library.

I did find the following link this morning, halfway down the page is a decent response.Android NFC foreground dispatch problem - Stack Overflow

As I said before, I will gladly pay you or anybody else for creating the library. I will then gladly put the library on the community for all to use.

Thank you Erel.
 

Peter Simpson

Expert
Licensed User
Longtime User
The current Library?

I'm just looking at the NFC library.

Erel asked, Do you only want the activity to read when the app is open?, my answer is yes.

I've played about the the manifest a lot and even added and xml file, but my app still does not take control of NFC fully :confused:
I have my app open, I scan the NFC TAG and my app opens again, giving me what I want, but that means my app is open twice.

This person had the exact same problem, but you told that person that a small library had to be written. But I might be getting confused http://www.b4x.com/forum/basic4andr...fc-foreground-dispatch-system.html#post136588

Well there will not be a problem with any other apps running in the background. They will only be running Nexus 7 tablets onsite and only my app will be installed on them all, nothing else. The client is purchasing about 21 tablets just to run my NFC app, but the app and only the app has to be able to read the NFC TAGS situated around their site.
 
Last edited:

Peter Simpson

Expert
Licensed User
Longtime User
Sorry for taking up your time, again!!!

Hello,
When I say opens twice, I mean my app is open, then once I scan the TAG my app also pops open as a NFC service, please look at the attached screen shot.

I've attached the original NFC file from this forum but with a layout added to it and a menu. In this example you will see that I've also messed about with the manifest a lot and also added an XML file.

I'm completely lost as this is taking up way too much of my time. I know that It's my fault but I just cant see what I'm missing and I have been all over the web looking for answers. All the solutions appear to say either Manifest with Foreground Dispatch System.

On Advanced NFC | Android Developers

Near the bottom the title is Using the Foreground Dispatch System is says:
The foreground dispatch system allows an activity to intercept an intent and claim priority over other activities that handle the same intent. Using this system involves constructing a few data structures for the Android system to be able to send the appropriate intents to your application. To enable the foreground dispatch system... and so on.

My screen shot is basically showing the same program twice. Once as an app, and once as a NFCservice.

Sorry for taking up so much of your time :-(

BTW, I also read http://www.b4x.com/forum/basic4andr...pting-sms-messages-background.html#post116193
 

Attachments

  • NFC.zip
    345.3 KB · Views: 747
  • Screenshot_2013-07-16-13-45-20.jpg
    Screenshot_2013-07-16-13-45-20.jpg
    10.8 KB · Views: 696
Last edited:

NeoTechni

Well-Known Member
Licensed User
Longtime User
I made the tutorial code as a project, but it doesn't show up when I scan a tag.
 

Attachments

  • nfc.zip
    6 KB · Views: 556
Top