Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
AN4618
Application note
Designing an NFC "Multiple NDEF record" application
using M24SR
Introduction
This application note explains how to develop an Android application to program with NFC
Multiple NDEF (NFC Data Exchange Format) Records an empty Tag of a device belonging
to the M24SR series using softwares listed in Table 1.
Table 1. Applicable softwares
Type
Root Part Numbers
Software
STSW-M24SR004
STSW-M24SR005
Figure 1. “Multiple NDEF records” application
January 2015
DocID027164 Rev 1
1/41
www.st.com
1
Contents
AN4618
Contents
1
Android application overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.1
About Android operating system . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.2
Android system component architecture view . . . . . . . . . . . . . . . . . . . . . . 6
1.3
2
1.2.1
Android architecture overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.2.2
Android API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Android Application Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.3.1
Application fundamentals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.3.2
Application components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.3.3
Intents and Intent filters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
How to create an Android Application for Multiple NDEF Records . . 14
2.1
Development environment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2.1.1
2.2
NFC Android API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2.2.1
2/41
Android.nfc Package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.3
Create a new project with eclipse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
2.4
Setup Android manifest file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
2.5
3
Prerequisites development environment . . . . . . . . . . . . . . . . . . . . . . . . 14
2.4.1
Permissions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
2.4.2
NFC feature . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
2.4.3
Intent filtering settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
Implementation of different Activities . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
2.5.1
MainActivity Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
2.5.2
Write NDEF Records Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . 24
2.5.3
NDEF Message Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
2.5.4
Final AndroidManifest.xml file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
2.5.5
Implementation Read Multiple NDEF Records . . . . . . . . . . . . . . . . . . . 34
2.5.6
Parsing of NDEF Records . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
2.5.7
Set Read Fragments with different Records . . . . . . . . . . . . . . . . . . . . . 35
How to use the NDEF records data . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
3.1
Connecting to Wi-Fi Network . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
3.2
Connecting to Bluetooth device . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
DocID027164 Rev 1
AN4618
4
5
Contents
Compilation of Android project to generate an application . . . . . . . . 39
4.1
Steps to execute command for project compilation . . . . . . . . . . . . . . . . . 39
4.2
Project debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
4.3
Running the project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
Revision history . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
DocID027164 Rev 1
3/41
3
List of tables
AN4618
List of tables
Table 1.
Table 2.
4/41
Applicable softwares . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Document revision history . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
DocID027164 Rev 1
AN4618
List of figures
List of figures
Figure 1.
Figure 2.
Figure 3.
Figure 4.
Figure 5.
Figure 6.
Figure 7.
“Multiple NDEF records” application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Android architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Android revision with corresponding API levels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Activity life cycle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Start project wizard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
New Android application wizard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
New Android application wizard completed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
DocID027164 Rev 1
5/41
5
Android application overview
AN4618
1
Android application overview
1.1
About Android operating system
Android is an operating system based on the Linux kernel and designed primarily for
touchscreen mobile devices such as smartphones and tablet computers. Initially developed
by Android, Inc., which Google backed financially and later bought in 2005, Android was
unveiled in 2007 along with the founding of the Open Handset Alliance: a consortium of
hardware, software, and telecommunication companies devoted to advancing open
standards for mobile devices. The first publicly available smartphone running Android, the
HTC Dream, was released on October 22, 2008.
1.2
Android system component architecture view
1.2.1
Android architecture overview
Basically android has the following layers (see Figure 2)
6/41
•
Application written in Java executing in Dalvik (the aim of the current application note)
•
Framework services and libraries written mostly in Java
•
Native library, daemons and services written in C or C++
•
The Linux kernel which includes:
–
Drivers for hardware
–
Networking
–
File system
–
Inter-process-communication
DocID027164 Rev 1
AN4618
Android application overview
Figure 2. Android architecture
$SSOLFDWLRQV
+RPH
&RQWDFWV
3KRQH
%URZVHU
$SSOLFDWLRQIUDPHZRUN
$FWLYLW\PDQDJHU
3DFNDJH
PDQDJHU
:LQGRZPDQDJHU
7HOHSKRQ\
PDQDJHU
&RQWHQW
SURYLGHUV
5HVRXUFH
PDQDJHU
9LHZV\VWHP
/RFDWLRQ
PDQDJHU
/LEUDLULHV
1RWLILFDWLRQ
PDQDJHU
$QGURLGUXQWLPH
6XUIDFHPDQDJHU
0HGLDIUDPHZRUN
64/LWH
2SHQ*/_(6
)UHH7\SH
:HE.LW
6*/
66/
OLEF
&RUHOLEUDULHV
'DOYLNYLUWXDO
PDFKLQH
/LQX[NHUQHO
'LVSOD\GULYHU
&DPHUDGULYHU
)ODVKPHPRU\
GULYHU
%LQGHU,3&
GULYHU
.H\SDGGULYHU
:L)LGULYHU
$XGLRGULYHUV
3RZHU
PDQDJHPHQW
06Y9
1.2.2
Android API
Android API is the upper software layer exposed to the developer. This API is based on the
core Java APIs and consists of a set of packages defining classes that ease the use of
Android feature and the device components. This API is built with multiple packages like:
•
Widget – UI components
•
Telephony – cell network, call, GSM, CDMA
•
Media – audio, video
•
Content – content providers
•
Database – SQLLite
•
XML – SAX, pull parser
•
Hardware – camera, sensor, usb, nfc
•
...
As Android is in constant development phase, packages are still improved by the Android
consortium, and new features are added. As an example NFC functionality appears at API
level 9 restricted to NDEF message access and has been improved since this API revision.
Figure 3 shows the whole Android revision and the associated API levels.
DocID027164 Rev 1
7/41
40
Android application overview
AN4618
Figure 3. Android revision with corresponding API levels
1.3
Android Application Introduction
1.3.1
Application fundamentals
Android application is primarily written in Java programming language. Source code is
converted to Java class files by the Java compiler. Then, Android SDK converts these Java
classes into optimized Dalvik executable file(s) (.dex suffix). Using the AAPT (Android Asset
Packaging Tool) tool, Dex files and application project related resources are packaged into
an APK: android package, which is an archive file with an “.apk” suffix. The APK generated
file self contains all the contents of an android application. The resulting APK file can be
deployed to an Android device by either the ADB tool in developing environment or by the
Android Play Store once the final application is published in release mode. The APK
package is used by the Android powered devices to install the application with a unique user
and group ID. Each application file is private to this generated user and other applications
cannot access this file.
8/41
DocID027164 Rev 1
AN4618
Android application overview
When launched by the operating system, the application runs, in its own process, upon its
own Dalvik virtual machine and is totally isolated from other running applications. In this
way, each application has access only to the components that it requires to do its work.
1.3.2
Application components
Android applications are written using components (Control, libraries) provided by the
Android Framework. Android Application strategy is to share application resources among
all application installed on an Android device. In this way application can publish its
resources so they can be used by other applications. Android system allows to
automatically instantiate the Java object owner of the desired component. This approach
implies in a first hand that application simply request to Android system to start the desired
component within the application that contain it, and in the second hand Android
applications don’t have an single entry point but rather get components that the system can
instantiate on demand.
Android components can be categorized in 4 main families:
•
Activities
•
Services
•
Broadcast receivers
•
Content providers
These components are asynchronously activated by messages called intents. On intent,
Android system finds the right component to respond to it and instantiates it if necessary by
a request from a content resolver method call.
1.3.3
Intents and Intent filters
Intent overview
Intent is a messaging object used to request an action from a component to other one and
then to facilitate communication between components. Intents are used on Android System
to:
Start an activity
•
Start a service
•
Deliver a broadcast
Structure of intent implicitly defines the two intent types:
•
Explicit intent: specifies the component to start by name. Typically use to start a
component from the same application as the component caller.
•
Implicit intent: declares a general action to perform without giving a component to start.
Caller doesn’t know the name of the capable component. Android system is then in
charge to find the appropriate component able to answer the caller request. Android
system looks for intent listed in the component’s intent filters declares in the manifest
file. If several components are identified, Android System displays a selectable list to
let the final user to decide which component to use.
Intent filters
Intent filters are xml structured definition stored with the component declaration in the
android manifest file (detailed later on in this application note). This structure is attached to a
component definition and declares the intent(s) the component is able to receive to perform
DocID027164 Rev 1
9/41
40
Android application overview
AN4618
action. By this way, user makes possible for other application to start an activity component
with a defined intent. Likewise, if component activity declaration doesn’t have an intent filter
declaration the activity is only start from its application owner.
Activities
Activity is a component belonging to an application and described in the android manifest of
the application it belongs to. The activity may provide a (partial) screen with which the user
can interact. Application is usually composed by several activities that are loosely bound to
each other. One activity is declared as the main activity which launched on the application
start. This main property is declared in the application manifest.xml file.
Each activity from the started application can start other activity, which present a new screen
to the user. Every time a new activity is started it is put in a stack and the previous one put in
stopped state while the Android system keeps the activity in a stack abiding to the basic
"last in, first out" stack mechanism also called back stack. When the current activity is
finished (action ended, back button pressed) it is popped from the back stack and destroy,
the activity on the top of the back stack is then resumed.
Activities life cycle
Activity life cycle is handled with callback methods that the system calls when the activity
transition between various states. Each activity must inherit Activity class (or an existing
subclass of it)
Activity Java skeleton
public class ExampleActivity extends Activity { @Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// The activity is being created.
}
@Override
protected void onStart() {
super.onStart();
// The activity is about to become visible.
}
@Override
protected void onResume() {
super.onResume();
// The activity has become visible (it is now "resumed").
}
@Override
protected void onPause() {
super.onPause();
// Another activity is taking focus (this activity is about to be
"paused").
}
@Override
protected void onStop() {
super.onStop();
10/41
DocID027164 Rev 1
AN4618
Android application overview
// The activity is no longer visible (it is now "stopped")
}
@Override
protected void onDestroy() {
super.onDestroy();
// The activity is about to be destroyed.
}
}
Figure 4 is an activity skeleton to show which callback method set has to be implemented to
handle the fundamental lifecycles methods. Taken together, those callbacks define the
entire life cycle of an activity managed by the Android system. The same figure shows that
developer can manage three different nested loops in the activity life cycle
•
Entire lifetime: Bound within the onCreate() and onDestroy() calls, activity should setup
or release resources on onCreate() and onDestroy() system call respectively.
•
Visible lifetime: Bound within onStart() and onStop() calls, user can see the activity onscreen and the required resources by the activity have to be maintains.
•
Foreground lifetime: Bound within the onResume() and onPause() calls, user can
interact with the activity’s screen.
DocID027164 Rev 1
11/41
40
Android application overview
AN4618
Figure 4. Activity life cycle
ĐƚŝǀŝƚLJ
ůĂƵŶĐŚĞĚ
ŽŶƌĞĂƚĞ;Ϳ
ŽŶZĞƐƚĂƌƚ;Ϳ
ŽŶ^ƚĂƌƚ;Ϳ
8VHUQDYLJDWHV
WRWKHDFWLYLW\
ŽŶZĞƐƵŵĞ;Ϳ
ƉƉƉƌŽĐĞƐƐ
ŬŝůůĞĚ
ĐƚŝǀŝƚLJ
ƌƵŶŶŝŶŐ
$QRWKHUDFWLYLW\FRPHV
LQWRWKHIRUHJURXQG
8VHUUHWXUQVWR
WKHDFWLYLW\
$SSVZLWKKLJKHU
SULRULW\QHHGPHPRU\
ŽŶWĂƵƐĞ;Ϳ
7KHDFWLYLW\LVQR
ORQJHUYLVLEOH
8VHUQDYLJDWHV
WRWKHDFWLYLW\
ŽŶ^ƚŽƉ;Ϳ
7KHDFWLYLW\LVILQLVKLQJRUEHLQJ
GHVWUR\HGE\WKHV\VWHP
ŽŶĞƐƚƌŽLJ;Ϳ
ĐƚŝǀŝƚLJƐŚƵƚ
ĚŽǁŶ
06Y9
Activity screen
Activity can directly managed its own graphic interface by implementing graphical object in a
static way. To provide more flexibility, Android propose a dedicated graphic object called
Fragment. Fragment represents a behavior or a portion of graphic user interface in an
activity. Multiple fragments can be combined in a single activity to facilitate reuse, screen
adaption. Fragment is always embedded in an activity and follows the activity lifecycle.
Broadcast receiver
Broadcast receiver is a component in charge to respond to the system -wide broadcast
announcement like a screen turn off message, a low battery message and so on.
Services
Services are application components which perform long-running operation in background
without providing any user interface. Service runs while the application is still alive
12/41
DocID027164 Rev 1
AN4618
Android application overview
independently the user switches to other activity (from the same application) to other
application.
Content providers
Content Providers is the component class in charge to provide mechanisms for defining
data security. They are standard interface to ensure data sharing between components
which not run in the same process. Application can manipulate its own set of data and store
it in file system, SQLite data base or external storage like SD. Other application can access
and modify this set of data by querying it through the content provided implemented by the
data owner application.
Content provider is a part of an application and is in charge to centralized data access from
other foreign components. It can also provide its own UI for working with the data it
provides. To get deeper understanding on content provider, reader can refer itself to
literature from web and more specifically on ‘calendar provider’ and ‘contact provider’ from
Android developer web site.
Application Manifest
Every Android Application is associated with a xml file called as AndroidManifest.xml.
Manifest file lists the permission the application requires to do its job and the minimum
android API level the application requires to be fully functional. It also describes
components (ie. Services, activity, broadcast receiver, content provider) belonging to the
application. Each component declaration gets a Java class name which implements the
component, a set of properties like a list of intent messages handled by the component.
DocID027164 Rev 1
13/41
40
How to create an Android Application for Multiple NDEF Records
AN4618
2
How to create an Android Application for Multiple
NDEF Records
2.1
Development environment
The developer has to setup the standard development environment for Android Application
development. The development environment allows the user to write source code,debug ,
build it with the right tool chain, and flash the application to the embedded targeted system
(i.e. the mobile phone running the android operating system).
2.1.1
Prerequisites development environment
•
Eclipse 3.6.2 (Helios) or greater with included Eclipse JDT plugin
•
Java Development Kit 7
•
Android SDK: Provides to the android application developers the Android API libraries
and tools necessary to build, test, trace and debug applications. Here is the list of the
main repositories in android SDK:
•
–
SDK Tools: contains tools for debugging and testing.
–
SDK Platforms tools: contains platform-dependent tools.
–
Documentation: offline copy of the android platforms APIs downloaded on
developer’s station.
–
SDK Platforms: store the SDK platform (for each version of android) – SDK
platforms can be downloaded on demand by the developer.
–
Samples for SDK: collection of samples provided by Google.
Android development tools (ADT) plugin (recommendation to fasten developments
steps): This plugin has been designed to give a powerful, integrated environment in
which to build android applications by extending the capabilities of Eclipse (IDE).
It is recommended to use eclipse with ADT installed as this solution is the fastest way to get
started. This solution eases the task to setup a new application project, to build the final
application in debug or release mode. During the pure development activity developers are
also supported by various integration tools and enhanced XML editor.
For more information about how to install and use eclipse or ADT according to its own
development station, reader can refer to Android developer website
[https://developer.android.com].
2.2
NFC Android API
NFC is a short-range wireless communication technology requiring a distance of 4 cm or
less to initiate a connection. User can exchange small payload of data between NFC
capable Android phone and NFC Tags. We are using M24SR/M24LR tags for exchanging
data between NFC supported mobile phone and NFC tags.NDEF (NFC Data Exchange
Format) is an NFC Forum data format. Many of the Android APIs are based on NFC Forum
standard.
14/41
DocID027164 Rev 1
AN4618
How to create an Android Application for Multiple NDEF Records
Android API is then able to handle 3 modes of operation:
•
Reader/Writer mode
•
P2P mode
•
Card emulation mode
Reader/Writer mode has been used in the current application.
2.2.1
Android.nfc Package
This package gives the access to the Near Field Communication functionality on NFC
capable Android. This package helps developer to easily read or write NDEF messages on
an external NDEF compliant NFC Tag.
Main class of the Android.nfc package
•
NfcAdapter
This class maps the local android phone’s NFC adapter. NfcAdapter is then the entry
point to perform NFC operations. Developer has to call the getDefaultAdapter() to
retrieve the default NFC adapter.
•
NfcManager
This class offers the NFC high level manager service used to obtain the instance of the
NfcAdapter. The instance can be retrieved by the call of getSystemService(String) with
NFC_SERVICE string given in parameter.
•
NdefMessage and NdefRecord
NdefMessage class represents the NDEF data message object implementation while
NdefRecord class represents the NDEF records carrying the NDEF message. Those
classes can be mapped on the NDEF NFC Forum specification. To construct a NDEF
message developer has to use the NdefMessage([byte]) call from a binary data that is
parsed by android API on NdefMessage creation. If the developer expects to use typed
data he may call NdefMessage(NderRecord, NdefRecords,….). NdefRecord object is
created according to type of record message developer wants to store in NDefMessage
(ie: RTD_TEXT, RTD_URI, RTD_SMART_POSTER, ..). RTD (Record Type Definition)
are specified by the NFC Forum and can be retrieving from their web site.
•
NfcEvent
Object used to wraps information associated with an NFC event usually included in
callbacks from NfcAdapter.
•
Tag
This class implements the Tag that is discovered (when a Tag is presented to the
Android phone’s NFC field). This object is immutable as it represents the state of the
Tag at the time it has been discovered. This object is used to retrieve the tag ID (getID()
call) and the properties of the Tag like the supported technologies (getTecList() call).
A new tag object is created every time a tag is discovered even if it is the same physical tag.
Developer must then ensure to always use the latest tag discovered to perform specific
action like TagTechnology interface manipulation.
When a tag is discovered, Android system creates a tag object, store it in an intent message
and requests for a startActivity with the created intent in parameter.
Depending on the tag characteristics and on the installed applications a four stage dispatch
solution is used to select the most appropriate activity to handle the current detected tag
DocID027164 Rev 1
15/41
40
How to create an Android Application for Multiple NDEF Records
AN4618
(see Figure 6 Tag Dispatch Startegy). Android system executes each stage in order and
complete dispatch as soon as a single matching activity is found.
16/41
•
Stage 1 – Foreground Activity dispatch: a foreground activity which has called
NfcAdapter.enableForegroundDispatch(…) is given the priority. This call is generally
done in the onResume() activity state callback. To release this priority developer has to
call NfcAdapter.disableForegroundDispatch(Activity) generally in Pause() activity state
callback.
•
Stage 2 – NDEF data dispatch: If the discovered tag contains at least an NDEF
message with a first Record with URI, SmartPoster or MimeData type Android system
call a startActivity() with ACTION_NDEF_DISCOVERED intent. Android System will
then look for a component ACTION_NDEF_DISCOVERED handling capable. If most
that one component is find, Android System requests to user to select the
application/component to launch to treat the pending intent. If none component is
register to handle this kind of intent dispatch move to stage 3.
•
Stage 3 – Tag Technology dispatch: Android System call a startActivity() with
ACTION_TECH_DISCOVERED and look for a component capable to handle current
tagTechnology. If any component is register to handle at least one technology
supported by the tag Android System goes to Stage 4.
•
Stage 4 – Fall-back dispatch: Android System call a startActivity() with
ACTION_TAG_DISCOVERED and look for a component capable to handle current
intent.
DocID027164 Rev 1
AN4618
2.3
How to create an Android Application for Multiple NDEF Records
Create a new project with eclipse
Once the development environment is installed (eclipse with ADT and Android SDK),
developer has to create his project by starting Eclipse IDE and select File/New/Project to
open the suitable create project wizard, as shown in Figure 5.
Figure 5. Start project wizard
DocID027164 Rev 1
17/41
40
How to create an Android Application for Multiple NDEF Records
AN4618
Then select Android/Android Application project and click on Next button to open the New
Android Application wizard (see Figure 6). In the text edit widget Application Name enter
“Multi_NDEF”. The Project Name and Package name text edits are automatically filled.
Figure 6. New Android application wizard
18/41
DocID027164 Rev 1
AN4618
How to create an Android Application for Multiple NDEF Records
Set the minimum Required SDK to API 11, Target SDK to API 14, and compile with at least
API14, then press Next several times until the project is created (see Figure 7). Ensure that
the Android API level14 SDK is installed on the developing station. Once the project is
created, build it to ensure that whole project creation settings are valid. If the build is
successful at this step, developer can start/debug the “Multi_NDEF” application on USB
connected android mobile phone to ensure that the application is correctly built.
Figure 7. New Android application wizard completed
DocID027164 Rev 1
19/41
40
How to create an Android Application for Multiple NDEF Records
2.4
AN4618
Setup Android manifest file
Once the project creation first step is completed, to use NFC functionality, developer has to
configure properly the android application settings in the AndroidManifest.xml.
2.4.1
Permissions
NFC Permissions
In order to use NFC capability, application must request the NFC permission. To do so, this
request must be specified in the manifest file by the following declaration:
<uses-permission android:name="android.permission.NFC" />
Wi-Fi Permissions
In order to use Wi-Fi capability to connect to Wi-Fi network through Multiple NDEF
Records Application, users must request Wi-Fi Permission. To do so, this request
Must be specified in the manifest file by the following declaration:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
Bluetooth Permissions
In order to use Bluetooth capability to connect to Wi-Fi network through Multiple NDEF
Records Application, users must request Wi-Fi Permission. To do so, this request
Must be specified in the manifest file by the following declaration:
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.BLUETOOTH" />
Internet Permissions
In order to internet capability in application, we again need to add permission for same.
<uses-permission android:name="android.permission.INTERNET" />
Contact Permissions
In order to access Contacts List in “Contacts NDEF Record” , we need to add following
permissions in Manifest file :
<uses-permission android:name="android.permission.READ_CONTACTS" />
20/41
DocID027164 Rev 1
AN4618
How to create an Android Application for Multiple NDEF Records
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
SMS/Network & Calling Permissions
In order to have network access to read/write SMS in “SMS NDEF Record”, we need to add
following permissions in Manifest file:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.CALL_PHONE" />
2.4.2
NFC feature
Specify that the application uses NFC by adding the following declaration:
<uses?feature
android:name="android.hardware.nfc" android:required="true" />
2.4.3
Intent filtering settings
As seen in the application overview section, component can be declared to be NFC intent
handler capable. To do so, an intent filter must be declared. Actually the application
identified by com.example.myfirstnfcapp in the manifest file is composed by a single
component which is an activity. This activity known as the main activity already has an intent
filter declaration:
<intent?filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent?filter>
This intent filter is declared specifically for main activity component to let Android System to
know which activity component to start on user request.
As the application get a single activity and as NFC intent can be handled in this main activity we
may declares a new intent filter to handle NDEF message when TAG is discovered.
In case activity component has to manage every kind of NDEF message we may add the
following intent filter declaration (solution that we keep for our source code example):
<intent?filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED"/>
</intent?filter>
DocID027164 Rev 1
21/41
40
How to create an Android Application for Multiple NDEF Records
AN4618
Complementary intent-filter
Android system also lets developer to refine the kind of intent he wants to act on. Keeping
the NDEF_DISCOVERED message, developer may want to only manage with a MIME type
of text/plain:
<intent?filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="text/plain" />
</intent?filter>
or wants to act on certain URI in the form of http://www.st.com:
<intent?filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:scheme="http" android:host="www.st.com"/>
</intent?filter>
In case developer wants the activity component been activated on ACTION_TECH
_DISCOVERED intent, he must write a XML file to be store in res/xml folder. Name of the
file is what the developer wish (ex: nfc_tech_filter.xml). This file lists the technology
supported by the component within a tech-list set as follows:
<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<tech?list>
<tech>android.nfc.tech.IsoDep</tech>
<tech>android.nfc.tech.NfcA</tech>
<tech>android.nfc.tech.NfcB</tech>
<tech>android.nfc.tech.NfcF</tech>
<tech>android.nfc.tech.NfcV</tech>
</tech?list>
</resources>
Once the XML NFC filter resources is created, the intent-filter on
ACTION_TECH_DISCOVERED is:
<intent?filter>
<action android:name="android.nfc.action.TECH_DISCOVERED"/>
</intent?filter>
<meta?data android:name="android.nfc.action.TECH_DISCOVERED"
android:resource="@xml/nfc_tech_filter" />
22/41
DocID027164 Rev 1
AN4618
How to create an Android Application for Multiple NDEF Records
The component activity will be then started by the Android system once a tag is discovered
with IsoDep, NfcA, NfcB or Nfcf capabilities. (Note that if the detected TAG gets a NDEF
message in and if a component is registered to treat NDEF intent the current application will
never receive the ACTION_TECH_DISCOVERED intent.)
In case developer expects his component is instantiate on ACTION_TAG_DISCOVERED intent
he must simply declare the following intent filter in the AndroidManifest.xml file:
<intent-filter>
<action android:name="android.nfc.action.TAG_DISCOVERED"/>
</intent-filter>
Multiple Screen Support Feature
In order to support different screen sizes like 3 inch, 4 inch etc. and different resolutions, we
need to add the following code in manifest file:
<supports-screens
android:anyDensity="true"
android:largeScreens="true"
android:normalScreens="true"
android:smallScreens="true"
android:xlargeScreens="true" />
2.5
Implementation of different Activities
There are many activities in the project.”MainActivity.java” is the main and startup activity of
the application. Frag_Write,frag_text,frag_url,frag_wifi_frag_bt,frag_sms etc. are the
fragment files used for each section of fragment in Write Mode of application.
Read_Fragment,Frag_Read_bt,Frag_read_text,Frag_read_url etc. are all the files related to
Read Mode of application for each NDEF Record represented in form of Fragments.
Mail,text,Contact,bt,SMS,Telephone,Wifi etc. files are implemented to show the real
functionality after reading different NDEF Records.
2.5.1
MainActivity Implementation
This is the main and startup activity of the application. There are two buttons in this file.
Read button is used to start Read_Fragment activity of the project.
Write Button click is used to start the Frag_Write activity of the project.
Read and Write Button are registered with OnClickListener as follows:
write = (Button)findViewById(R.id.button2);
write.setOnClickListener(new OnClickListener()
{
DocID027164 Rev 1
23/41
40
How to create an Android Application for Multiple NDEF Records
AN4618
public void onClick(View v)
{
// TODO Auto-generated method stub
//Log.i("BTN", "NDEF FORMAT");
try
{
Intent i = new Intent(getApplicationContext()
,Frag_Write.class);
startActivity(i);
}
catch(Exception e)
{
Toast toast =
Toast.makeText(getApplicationContext(),
e.toString(), Toast.LENGTH_LONG);
toast.show();
}}});
read = (Button)findViewById(R.id.button1);
read.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
// TODO Auto-generated method stub
//Log.i("BTN", "NDEF FORMAT");
Toast toast = Toast.makeText(getApplicationContext(),
"Please bring the tag close to phone",
Toast.LENGTH_LONG);
toast.show();
}});
2.5.2
Write NDEF Records Implementation
Frag_Write Activity is used to write multiple types of NDEF Records in M24SR Tag. All the
Records are programmed using a Write Button registered in this file as follows :
mWriteTagButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
initialize();
}
OnClick Event of this Write Button calls a function enableWriteMode() as follows:
private void enableWriteMode() {
mInWriteMode = true;
24/41
DocID027164 Rev 1
AN4618
How to create an Android Application for Multiple NDEF Records
try {
// set up a PendingIntent to open the app when a tag is scanned
PendingIntent pendingIntent =
PendingIntent.getActivity(this, 0, new Intent(this,
getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
IntentFilter tagDetected = new
IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
IntentFilter[] filters = new IntentFilter[] { tagDetected };
mAdapter.enableForegroundDispatch(this, pendingIntent, filters, null);
}
catch(Exception e){
Toast toast = Toast.makeText(getApplicationContext(),"Problem capturing
tag" + e.toString(), Toast.LENGTH_SHORT);
toast.show();}}
After the Write Button is clicked by user, application will wait for an intent generated on
bringing mobile phone near to Tag. OnNewIntent() is implemented as follows:
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
WriteTag(Tag tag) is called inside the OnNewIntent() to program the NDEF Records.
Creating Application Record
In order to create Application Record, following code is added in WriteTag() function of
Frag_Write.java
NdefRecord appRecord =
NdefRecord.createApplicationRecord("com.example.multi_ndef");
Creating Text Record
In order to create a text record in application, following code is added in WriteTag()
try {
textRecord = createTextRecord(getText(),ENGLISH, encodeInUtf8);
}
catch(Exception e)
{
Toast toast = Toast.makeText(getApplicationContext(),
"Text Conversion error "+ e.toString(), Toast.LENGTH_SHORT);
toast.show();
}
There is a function CreateTextRecord() that is required to be added in Frag_Write.java
which is called inside WriteTag() function.
DocID027164 Rev 1
25/41
40
How to create an Android Application for Multiple NDEF Records
AN4618
public NdefRecord createTextRecord(String payload, Locale locale, boolean
encodeInUtf8) {
byte[] langBytes =
locale.getLanguage().getBytes(Charset.forName("US-ASCII"));
Charset utfEncoding = encodeInUtf8 ? Charset.forName("UTF-8")
: Charset.forName("UTF-16");
byte[] textBytes = payload.getBytes(utfEncoding);
int utfBit = encodeInUtf8 ? 0 : (1 << 7);
char status = (char) (utfBit + langBytes.length);
byte[] data = new byte[1 + langBytes.length +
textBytes.length];
data[0] = (byte) status;
System.arraycopy(langBytes, 0, data, 1, langBytes.length);
System.arraycopy(textBytes, 0, data, 1 + langBytes.length,
textBytes.length);
NdefRecord record = new NdefRecord(NdefRecord.TNF_WELL_KNOWN,
NdefRecord.RTD_TEXT, new byte[0], data);
return record;
}
Creating URI Record
In order to create/add URI type record in multiple NDEF Records implementation, following
source code is added in WriteTag() function of Frag_Write.java
In the below code, we make use of in-built function of createUri() provided by android.nfc
package.
URI Type records includes different types like URL, SMS, Mail, Telephone, Location etc.
URL NDEF Record
try {
uriRecord = NdefRecord.createUri(getUri());
}
catch (Exception e )
{
Toast toast = Toast.makeText(getApplicationContext(),
"Uri Conversion error "+ e.toString(),
Toast.LENGTH_SHORT);
toast.show();
}
Mail NDEF Record
To create NDEF Record for Mail, we need to create object of NDEFRecord and call
createUri(Mail Payload) with payload of Mail format.
NdefRecord MailRecord = NdefRecord.createUri(Mailpayload);
MailPayload is String class type variable which is initialized as follows in getMail() function
called by initListener().
26/41
DocID027164 Rev 1
AN4618
How to create an Android Application for Multiple NDEF Records
private void getMail()
{
Sto=to.getText().toString();
Scc=cc.getText().toString();
Sbcc=bcc.getText().toString();
Ssubject=subject.getText().toString();
String Smessage=body.getText().toString();
Mailpayload="mailto:"+Sto;
if(!Ssubject.isEmpty())
{
Mailpayload+="?subject="+Ssubject;
}
if(!Scc.isEmpty())
{
Mailpayload+="&cc="+Scc;
}
if(!Sbcc.isEmpty())
{
Mailpayload+="&bcc="+Sbcc;
}
if(!Smessage.isEmpty())
{
Mailpayload+="&body="+Smessage;
}}
SMS NDEF Record
SMS NDEF record is implemented using createUri() function of NDEFRecord class.
NdefRecord SMSRecord = NdefRecord.createUri(SMSpayload);
getSMS() function is called to initialize the SMSPayload with different parameters required
for SMS.
private void getSMS()
{
noOfContacts=ma.getnoOfContacts();
MultiContacts=ma.getMultiContacts();
String Snumber;
if(noOfContacts==1)
{
Snumber=numbers.getText().toString();
}
else
{
if(!numbers.getText().toString().isEmpty())
{
Snumber=MultiContacts+";"+numbers.getText().toString();
DocID027164 Rev 1
27/41
40
How to create an Android Application for Multiple NDEF Records
AN4618
}
else
{
Snumber=MultiContacts;
}
}
String Smessage=message.getText().toString();
SMSpayload="sms:"+Snumber+"?body="+Smessage;
}
Telephone NDEF Record
Telephone NDEF Record is implemented using createUri() function of NDEFRecords.
Telephone Payload is filled as below:
NdefRecord TeleRecord = NdefRecord.createUri(Telepayload);
getTelphone() function to initialize the Telepayload is defined as below :
private void getTelephone()
{
String Snumber=telephone.getText().toString();
Telepayload="tel:"+Snumber;
}
Location NDEF Record
Location NDEF Record will be defined using createUri() function and assigning to object of
NDEFRecord class as below :
NdefRecord LocationRecord = NdefRecord.createUri(Locationpayload);
Location Payload is initialized as below:
private void getLocation()
{
String Slatitude=latitude.getText().toString();
String Slongitude=longitude.getText().toString();
Locationpayload="geo:"+Slatitude+","+Slongitude;
Creating V Card NDEF Record
V- Card NDEF Record format is defined as below in WriteTag() function of Frag_Write.java
28/41
DocID027164 Rev 1
AN4618
How to create an Android Application for Multiple NDEF Records
NdefRecord VcardRecord = new NdefRecord(NdefRecord.TNF_MIME_MEDIA, "text/xvcard".getBytes(), new byte[0], v_data);
v_data is an array of byte type which is initialized by VCard() method as below :
public byte [] VCard()
{
try {
String vcardString = "";
String _Vcard ="BEGIN:VCARD\nVERSION:2.1\n";
vcardString =
vcardString + "N:"+v_name.getText().toString()+"\n";
vcardString =
vcardString + "EMAIL:"+v_mail.getText().toString()+"\n";;
vcardString =
vcardString + "ADR:"+v_add.getText().toString()+"\n";
vcardString = vcardString +
"TEL:"+v_number.getText().toString()+"\n";
vcardString = _Vcard + vcardString + "END:VCARD";
byte[] card_payload = vcardString.getBytes(Charset.forName("US-ASCII"));
return card_payload;
}
catch (Exception e)
{
Toast toast =
Toast.makeText(getApplicationContext(),"vCard formation error "+
e.toString(), Toast.LENGTH_SHORT);
toast.show();
return null;
} }
Creating Bluetooth NDEF Record
Bluetooth NDEF Record is defined as below :
NdefRecord BTcardRecord = new NdefRecord(NdefRecord.TNF_MIME_MEDIA,
mimeBytesBT,
new byte[0], payloadBT);
payloadBT is the complete format for Bluetooth Handover message:
byte[] payloadBT = btData();
NDEF Format is initialized in btData().
DocID027164 Rev 1
29/41
40
How to create an Android Application for Multiple NDEF Records
AN4618
Creating Wi-Fi NDEF Record
Wi-Fi NDEF Record is defined as below :
NdefRecord cardRecord = new NdefRecord(NdefRecord.TNF_MIME_MEDIA,
mimeBytes,
new byte[0], payload);
payload is an array of byte type which is initialized by data() function to fill the required bytes
of Wi-Fi NDEF Record.
byte[] payload = data();
NDEF Format is initialized in btData().
2.5.3
NDEF Message Implementation
After declaration of all the NDEF Records in Write Tag() function of Frag_Write.java.The
next step is to define NDEF Message with multiple NDEF Records.
Below is the code to declare the object of NDEF Message class to get multiple NDEF
Records.
NdefMessage message = new NdefMessage(new NdefRecord[] {
cardRecord,textRecord,uriRecord,BTcardRecord,VcardRecord,SMSRecord,MailRec
ord,TeleRecord,LocationRecord,appRecord});
In the above code, different object of NDEF Record are passed as parameter to
NDEFMessage class.
Writing NDEFMessage to Card
ndef.writeNdefMessage(message);
2.5.4
Final AndroidManifest.xml file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.multi_ndef"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.NFC" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
30/41
DocID027164 Rev 1
AN4618
How to create an Android Application for Multiple NDEF Records
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"
/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"
/>
<uses-permission android:name="android.permission.WRITE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-feature
android:name="android.hardware.nfc"
android:required="true" />
<supports-screens
android:anyDensity="true"
android:largeScreens="true"
android:normalScreens="true"
android:smallScreens="true"
android:xlargeScreens="true" />
<application
android:name="com.example.multi_ndef.CNFCInterface"
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:logo="@drawable/st"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.multi_ndef.MainActivity"
android:label="@string/app_name"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.multi_ndef.CardActivity"
android:label="@string/app_name" >
DocID027164 Rev 1
31/41
40
How to create an Android Application for Multiple NDEF Records
AN4618
<intent-filter>
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name="com.example.multi_ndef.Write"
android:label="@string/app_name"
android:screenOrientation="portrait" >
</activity>
<activity
android:name="com.example.multi_ndef.Read"
android:label="@string/app_name"
android:screenOrientation="portrait" >
<!--
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED" />
<data android:mimeType="application/vnd.wfa.wsc" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter> -->
</activity>
<activity
android:name="com.example.multi_ndef.text"
android:label="@string/app_name"
android:screenOrientation="portrait" >
</activity>
<activity
android:name="com.example.multi_ndef.bt"
android:label="@string/app_name"
android:screenOrientation="portrait" >
</activity>
<activity
android:name="com.example.multi_ndef.uri"
android:label="@string/app_name"
android:screenOrientation="portrait" >
</activity>
<activity
android:name="com.example.multi_ndef.wifi"
android:label="@string/app_name"
android:screenOrientation="portrait" >
</activity>
<activity
android:name="com.example.multi_ndef.contact"
android:label="@string/app_name"
32/41
DocID027164 Rev 1
AN4618
How to create an Android Application for Multiple NDEF Records
android:screenOrientation="portrait" >
</activity>
<activity
android:name="com.example.multi_ndef.SMS"
android:label="@string/title_activity_sms"
android:screenOrientation="portrait" >
</activity>
<activity
android:name="com.example.multi_ndef.Mail"
android:label="@string/title_activity_mail"
android:screenOrientation="portrait" >
</activity>
<activity
android:name="com.example.multi_ndef.Telephone"
android:label="@string/title_activity_telephone"
android:screenOrientation="portrait" >
</activity>
<activity
android:name="com.example.multi_ndef.Location"
android:label="@string/title_activity_location"
android:screenOrientation="portrait" >
</activity>
<activity
android:name="com.example.multi_ndef.Frag_Write"
android:label="@string/app_name"
android:screenOrientation="portrait" >
</activity>
<activity
android:name="com.example.multi_ndef.Read_Fragment"
android:label="@string/title_activity_read__fragment" >
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED" />
<data android:mimeType="application/vnd.wfa.wsc" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name="com.example.multi_ndef.Frag_read_text"
android:label="@string/title_activity_frag_read_text" >
</activity>
<activity
android:name="com.example.multi_ndef.Frag_read_bt"
android:label="@string/title_activity_frag_read_bt" >
DocID027164 Rev 1
33/41
40
How to create an Android Application for Multiple NDEF Records
AN4618
</activity>
<activity
android:name="com.example.multi_ndef.Frag_read_wifi"
android:label="@string/title_activity_frag_read_wifi" >
</activity>
<activity
android:name="com.example.multi_ndef.Frag_read_mail"
android:label="@string/title_activity_frag_read_mail" >
</activity>
<activity
android:name="com.example.multi_ndef.Frag_read_contact"
android:label="@string/title_activity_frag_read_contact" >
</activity>
<activity
android:name="com.example.multi_ndef.Frag_read_url"
android:label="@string/title_activity_frag_read_url" >
</activity>
<activity
android:name="com.example.multi_ndef.Frag_read_sms"
android:label="@string/title_activity_frag_read_sms" >
</activity>
<activity
android:name="com.example.multi_ndef.Frag_read_telephone"
android:label="@string/title_activity_frag_read_telephone" >
</activity>
<activity
android:name="com.example.multi_ndef.Frag_read_location"
android:label="@string/title_activity_frag_read_location" >
</activity>
</application>
</manifest>
2.5.5
Implementation Read Multiple NDEF Records
When user will click Read button of MainActivity.java class, it will call on click Listener
event. It will generate a toast as below:
Toast toast = Toast.makeText(getApplicationContext(),
"Please bring the tag close to phone", Toast.LENGTH_LONG);
toast.show();
When user brings mobile phone near to Tag after generation of Toast message, it will
automatically called Read_Fragment.java.
34/41
DocID027164 Rev 1
AN4618
How to create an Android Application for Multiple NDEF Records
Read_Fragment.java is called when we mention this activity in “NDEF_DISCOVERED”
intent-filter in “AndroidManifest.xml”.
<activity
android:name="com.example.multi_ndef.Read_Fragment"
android:label="@string/title_activity_read__fragment" >
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED" />
<data android:mimeType="application/vnd.wfa.wsc" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
2.5.6
Parsing of NDEF Records
When mobile phone is brought in close proximity to Tag, an intent of NDEF_DISCOVERED
is generated and Read_Fragment.java is invoked.
NDEFMessage class is used to receive the message read from Tag .NdefMessage is then
parsed into NdefRecords.
Intent intent = getIntent();
if(intent.getType() != null &&
intent.getType().equals(MimeType.AppName)) {
Parcelable[] rawMsgs =
getIntent().getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
NdefMessage msg = (NdefMessage) rawMsgs[0];
NdefRecord cardRecord
= msg.getRecords()[0];
NdefRecord cardRecord2 = msg.getRecords()[1];
NdefRecord cardRecord3 = msg.getRecords()[2];
NdefRecord cardRecord4 = msg.getRecords()[3];
NdefRecord cardRecord5 = msg.getRecords()[4];
NdefRecord cardRecord6 = msg.getRecords()[5];
NdefRecord cardRecord7 = msg.getRecords()[6];
NdefRecord cardRecord8 = msg.getRecords()[7];
NdefRecord cardRecord9 = msg.getRecords()[8];
There are different types of NDEF Records which are stored in different types of objects of
NdefRecords class.
2.5.7
Set Read Fragments with different Records
NdefRecords are initialized into different byte [] array buffer using getPayload() function of
NdefRecords class.
DocID027164 Rev 1
35/41
40
How to create an Android Application for Multiple NDEF Records
WiFi =
cardRecord.getPayload();
Text =
cardRecord2.getPayload();
UriValue =
BT =
AN4618
cardRecord3.getPayload();
cardRecord4.getPayload();
Contact = cardRecord5.getPayload();
Sms = cardRecord6.getPayload();
Mail = cardRecord7.getPayload();
Telephone = cardRecord8.getPayload();
Location = cardRecord9.getPayload();
This is done inside the Read_Fragment.java class in onCreate(Bundle savedInstanceState)
CNFCInterface.java class is the application class of the project which is used to set and get
different types of buffers.
Data is extracted from Payload of NdefRecords and are saved inside the Byte buffer of
CNFCInterface.java
ma.setUriData(UriValue);
ma.setWiFiData(WiFi);
ma.setBTData(BT);
ma.setContactData(Contact);
ma.setSMSData(Sms);
ma.setMailData(Mail);
ma.setTelephoneData(Telephone);
ma.setLocationData(Location);
These buffers are invoked inside the Fragment classes for different NDEFRecords.
Frag_read_bt.java code is as below:
ma = (CNFCInterface)getActivity().getApplication();
message =ma.getBTData();
Frag_Read_Mail.java code is as below:
mailData=new String(ma.getMailData(),Charset.forName("US-ASCII"));
item=mailData;
36/41
DocID027164 Rev 1
AN4618
3
How to use the NDEF records data
How to use the NDEF records data
There are different types of NdefRecords:
•
text
•
URL
•
Wi-Fi
•
Bluetooth
•
V-Card
•
Mail
•
SMS
•
etc.
There are cases in which data can be utilized further after completing the read process of
M24SR Tag. In case of Wi-Fi Handover Record, we can use SSID and Password to connect
to Wi-Fi network. Bluetooth Device Name can be used to connect. URL can be used to open
in the browser. Contacts read from the Tag can be used to add in the Contact List. Mail Data
can be used to send a mail.
3.1
Connecting to Wi-Fi Network
Wi-Fi NDEF Handover Message read from the M24SR Tag provides us with different bytes
of useful information. Network SSID and Password are the key components which can be
further utilized to connect to a Wi-Fi network.This is done in wifi.java class.
WifiInfo wifiinfo=wifiManager.getConnectionInfo();
ssid_info=wifiinfo.getSSID();
ConnectivityManager connManager = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWifi =
connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
This also requires the Wi-Fi permission which are mentioned inside the
AndroidManifest.xml file.
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
3.2
Connecting to Bluetooth device
In Bluetooth handover message, we get many useful parameters for Bluetooth device. In
this MAC address of the device and class of device are the key components.
We can use Bluetooth class to extract the name of the device from MAC Address.
DocID027164 Rev 1
37/41
40
How to use the NDEF records data
AN4618
In case of connection to Bluetooth A2DP class, we need to invoke following functions in
bt.java class.
For Bluetooth A2DP device connection, functions are not available directly in package. We
call the functions using an interface.
Bluetooth interfaces are defined inside the stubs folder located at the root of the project.
Build.xml is required to build the project using ant tool.
device1.createBond();
bluetoothA2dp.connect(device1);
The above two functions are called using interface defined in stubs folder.
38/41
DocID027164 Rev 1
AN4618
4
Compilation of Android project to generate an application
Compilation of Android project to generate an
application
As mentioned in Section 2.3, Eclipse was used to create new Android Project and to create
its source files. After completion of Java files used in project, we need to compile and then
run the project.
ANT is a tool or plug-in used along with Eclipse to compile and run the project. It must be
installed on the system for debugging and running of this application. It is used in the cases
when we are using aidl files in project as we did in Section 3.2 for connecting to Bluetooth
devices.
For compilation of project using ANT Tool, we need to execute commands using Command
Prompt.
4.1
Steps to execute command for project compilation
1.
Go to cmd prompt (Command Prompt on your PC)
2.
Go to the project directory folder and then type the following command
3.
In place of <project-name>write the name of project, in place of target –ID , specify the
android target as android-15 or android-14 etc. and in place of <path –to project>, type
the full path of your project., android update project --name <project_name> --target
<target_ID> --path <path_to_your_project>
Example: - Name of my Project is A2DPActivity and is located at C:\Usr\androidWS
4.2
4.3
Project debugging
1.
Go to Command Prompt and change directory to your project directory.
2.
Type ant debug command and Press Enter Key to debug the project through
Command Prompt using ANT Tool.
Running the project
1.
Go to Command Prompt and change directory to your project directory.
2.
Type ant release command and Press Enter Key to compile the project in release
mode through Command Prompt using ANT Tool.
DocID027164 Rev 1
39/41
40
Revision history
5
AN4618
Revision history
Table 2. Document revision history
40/41
Date
Revision
29-Jan-2015
1
Changes
Initial release.
DocID027164 Rev 1
AN4618
IMPORTANT NOTICE – PLEASE READ CAREFULLY
STMicroelectronics NV and its subsidiaries (“ST”) reserve the right to make changes, corrections, enhancements, modifications, and
improvements to ST products and/or to this document at any time without notice. Purchasers should obtain the latest relevant information on
ST products before placing orders. ST products are sold pursuant to ST’s terms and conditions of sale in place at the time of order
acknowledgement.
Purchasers are solely responsible for the choice, selection, and use of ST products and ST assumes no liability for application assistance or
the design of Purchasers’ products.
No license, express or implied, to any intellectual property right is granted by ST herein.
Resale of ST products with provisions different from the information set forth herein shall void any warranty granted by ST for such product.
ST and the ST logo are trademarks of ST. All other product or service names are the property of their respective owners.
Information in this document supersedes and replaces information previously supplied in any prior versions of this document.
© 2015 STMicroelectronics – All rights reserved
DocID027164 Rev 1
41/41
41