Android Tutorial NFC - Reading and Writing

Status
Not open for further replies.
NFC v2.00 adds support for low level access to the NFC features. This allows reading and writing from NFC tags.

The NFC library provides three features:
- Reading Ndef tags based intent filters: Reading NDEF data from NFC tags
- Sending data between two devices (Android Beam): https://www.b4x.com/android/forum/threads/60731/#content
- Low level access to the tag.

This tutorial explains how you can use the low level access to read and write Ndef tags. It is also possible to extend it to other types of tags. However you will need to implement the required protocol yourself.

upload_2016-3-9_16-12-25.png


When a tag is scanned, the system sends an intent. The first step is to call NFC.EnableForegroundDispatch in Activity_Resume. This will force the system to send the intent to our activity instead of sending it to a different app.
You should call NFC.DisableForegroundDispatch in Activity_Pause.

Activity_Resume will be called when an intent is sent to our activity. We need to check two things:
1. This intent is related to a tag discovery.
2. This is a new intent.

B4X:
Sub Activity_Resume
   'forces all nfc intents to be sent to this activity
   nfc.EnableForegroundDispatch
   Dim si As Intent = Activity.GetStartingIntent
   'check that the intent is a new intent
   If si.IsInitialized = False Or si = prevIntent Then Return
   prevIntent = si
   If si.Action.EndsWith("TECH_DISCOVERED") Or si.Action.EndsWith("NDEF_DISCOVERED") Or si.Action.EndsWith("TAG_DISCOVERED") Then
      'work with the intent
     End If
   End If
End Sub

Each NFC tag can support multiple types of technologies.
NFC.GetTechList will return the list of supported technologies.
You can see the full list of technologies here: http://developer.android.com/reference/android/nfc/tech/TagTechnology.html

Assuming that the tag supports a technology that is relevant to our app, we create a TagTechnology object with the technology name and then connect to the tag:
B4X:
If techs.IndexOf("android.nfc.tech.Ndef") > -1 Then
   TagTech.Initialize("TagTech", "android.nfc.tech.Ndef" , si)
   'Connect to the tag
   TagTech.Connect
Else
The technology class sets the actual type of TagTech.

The Connected event will be raised when the connection is established. Make sure to check the success parameter as it can fail if the user moved the device during the connection.

Once connected we can start calling the technology specific APIs. The NFC library doesn't expose these APIs. You should instead use JavaObject or TagTechnology.RunAsync to call these methods.
You can find the APIs here: http://developer.android.com/reference/android/nfc/tech/NfcA.html (for NfcA).

There are two types of methods: blocking (I/O) and non-blocking.
You should use TagTechnology.RunAsync to call any of the blocking methods. The RunAsync event will be raised when the operation completed (the call itself will be executed on a background thread).

Example of reading Ndef records (API: http://developer.android.com/reference/android/nfc/tech/Ndef.html):
B4X:
Private Sub ReadNdef
   TagTech.RunAsync("ReadNdef", "getNdefMessage", Null, 0)
End Sub

Private Sub ReadNdef_RunAsync (Flag As Int, Success As Boolean, Result As Object)
   Log($"Reading completed. Success=${Success}, Flag=${Flag}"$)
   ListView1.Clear
   If Success Then
     If Result = Null Then
       ToastMessageShow("No records found.", False)
     Else
       Dim message As JavaObject = Result
       Dim records() As Object = message.RunMethod("getRecords", Null)
       For Each r As NdefRecord In records
         Dim b() As Byte = r.GetPayload
         ListView1.AddSingleLine(BytesToString(b, 0, b.Length, "utf8"))
       Next
     End If
   End If
End Sub

The attached example shows how to read and write to Ndef tags. This is a popular and simple format.

Versions:

- This example is compatible with Android 4.1+ (API 16). The minimum version if you don't use NFC.CreateMimeRecord is Android 4.0 (API 14).
- NFC v2.0+: https://www.b4x.com/android/forum/threads/updates-to-internal-libraries.59340/#post-408085
- ViewsEx 1.11+: https://www.b4x.com/android/forum/threads/updates-to-internal-libraries.59340/#content
- B4A v5.80+ (you can use older versions by creating a new layout without the custom views, the minimum version is v5.00).
 

Attachments

  • AdvancedNFC.zip
    8.9 KB · Views: 2,729
Last edited:

ovt001

Member
Licensed User
Hello everybody,
I tried to download the Advanced NFC from Erel en test it into my B4A 8.x (Android 28), but when I run it, I receive this message into the logs (Manifest Editor)

B4X:
'This code will be applied to the manifest file during compilation.
'You do not need to modify it in most cases.
'See this link for for more information: https://www.b4x.com/forum/showthread.php?p=78136
AddManifestText(
<uses-sdk android:minSdkVersion="16" android:targetSdkVersion="19"/>
<supports-screens android:largeScreens="true" 
    android:normalScreens="true" 
    android:smallScreens="true" 
    android:anyDensity="true"/>)
SetApplicationAttribute(android:icon, "@drawable/icon")
SetApplicationAttribute(android:label, "$LABEL$")
'End of default text.

Can somebody help me.
thank's
O.
 

ovt001

Member
Licensed User
Hi DonManFred,
If you have a look on the first page of this post, you will see that Erel put a sample program (Advanced NFC). I try it and I receive the error into the log file when I compile it.
That's the reason that I reopen this thread.
The logs shows this message:
"The recommended value for androidtargetSdkVersion is 26 or above (manifest editor) warning #31"

When I click on the message into the log, start the Manifest Editor with this code.
B4X:
'This code will be applied to the manifest file during compilation.
'You do not need to modify it in most cases.
'See this link for for more information: https://www.b4x.com/forum/showthread.php?p=78136
AddManifestText(
<uses-sdk android:minSdkVersion="16" android:targetSdkVersion="19"/>
<supports-screens android:largeScreens="true" 
    android:normalScreens="true" 
    android:smallScreens="true" 
    android:anyDensity="true"/>)
SetApplicationAttribute(android:icon, "@drawable/icon")
SetApplicationAttribute(android:label, "$LABEL$")
'End of default text.

And I don't know what I need to do.
thank you
O.
 

DonManfred

Expert
Licensed User
If you have a look on the first page of this post, you will see that Erel put a sample program (Advanced NFC). I try it and I receive the error into the log file when I compile it.
That's the reason that I reopen this thread.
The logs shows this message:
"The recommended value for androidtargetSdkVersion is 26 or above (manifest editor) warning #31"
But you DID NOT posted this WARNING (a warning is not a error)!!!

Check this thread: https://www.b4x.com/android/forum/threads/android-jar-targetsdkversion-minsdkversion.87610/
Also note ALL the infos/turorials in this thread!

Start a new thread for any new question you have.
 
Status
Not open for further replies.
Top