NFC Android applications development guidelines

fansbutterflyMobile - Wireless

Jul 19, 2012 (5 years and 1 month ago)

1,581 views






AFSCM

Android
d
evelopment
g
uidelines


p
1
/
40


Copyright © AFSCM 20
11










NFC Android applications development guidelines









RELEASE

1.
1

Date


27
/
03
/2012

Reference

120327
-

AFSCM TECH
-

LIVBL
-

Android Development Guidelines
-

v1.1.doc




AFSCM
Android

development guidelines
v1.1

p
2
/
40


Copyright © AFSCM
2012



Name

Company

Au
thors

Pierre Le Pallec

Bouygues Telecom

Mathieu Amiel

NRJ mobile

Sébastien Hallay

Orange

Michaël Bensimon

Thierry Simon

SFR

Editors

Sébastien Gauthier

AFSCM

Sébastien Hallay

Orange

Document manager

Sébastien Hallay

Orange

Approval

Sébastien Hall
ay

Orange


Document management


Version

Date

Chapters

Modification

1.0

15/11/2011


2.5.4

2.10, 4.1.4

2
.8


2.2.1

2.5.3

First public release

Added
application

update rule

Updated
Smart Card API
permissions (
seek
-
for
-
android 2.2.2
)

Metadata: added
NFC
-
Serv
ice
-
Type
-
x
,
NFC
-
Service
-
Nb
, NFC
-
Service
-
Label
-
x;

renamed and changed value for
NFC
-
Service
-
AID
-
x

Added “
却物ng⁅ncoT楮g⁍慮慧敭敮t
” section

Added “Application signature” section and rules

1⸰⸱

14I12I2011

2⸸⸲

Fix: added the “=” in
0‼⁸ <
=

N䙃
-
卥Sv楣i
-


Fix: removed “(several occurrences possible) for
N䙃
-
卥牶楣S
-
䅉M
-
x


1


I

I
2012

2⸱⸲

2⸵⸳

2⸶⸶

2⸷.
2

2⸷.
3

2⸸⸲


2⸱..1

4⸱⸴

䅬l

䍯mp汥瑥T⁲畬攠#4: 獹獴敭 捬慳獥猠楮⁴桥⁁ K

卩gn慴畲攠捡c⁢攠prov楤敤⁩n⁓ 䄱Aor⁍M5⁦ rmat

MoT楦i敤
P2P⁳ c瑩t



啳楮g⁁ d牯楤⁂ am

啰d慴ad
H䍉Cm慮慧em敮e

䅤d敤⁳e捴con on⁥
x瑥牮慬a剔R m慮慧em敮e

䅤d敤⁸桤p椠牥獯汵瑩on;⁡汬ow敤⁵獥eo映瑨攠摡獨⁣h慲慣瑥爠楮 瑨攠
N䙃
-
䅰A
-
N慭e

P牥捩r敤⁵獥f
瑨攠
uses
-
library
tag

Added section “
啳楮g⁆ reg牯unT⁄楳i慴捨⁷楴i⁎M䕆


U
p
T慴aT

links to android developers’resources; updated

牵汥l

numb敲e

慮T⁳ ur捥c捯T攠獡spl敳

⡮o眠捯mp汩慮琠睩瑨wo汤
慮T敷⁏p敮⁍ob楬攠AP䤠I牯m⁓䥍䅬汩慮c攩



AFSCM
Android

development guidelines
v1.1

p
3
/
40


Copyright © AFSCM
2012


TABLE
OF CONTENTS

________________________________
____________________________


1

I
NTRODUCTION

................................
................................
................................
...................

5

1.1

Context

................................
................................
................................
................................
..................

5

1.2

Copyright license

................................
................................
................................
................................
...

5

1.3

Purpose and content of this document
................................
................................
................................
.

6

1.4

References

................................
................................
................................
................................
.............

8

1.5

Abbreviation

................................
................................
................................
................................
..........

8

2

M
ANAGEMENT RULES

................................
................................
................................
..........

10

2.1

Development process

................................
................................
................................
..........................

10

2.1.1

Specification

................................
................................
................................
................................

10

2.1.2

Dependencies in terms of device properties and features

................................
........................

10

2.1.3

Usage of personal data

................................
................................
................................
...............

11

2.1.4

Testing

................................
................................
................................
................................
.........

11

2.2

Coding rules

................................
................................
................................
................................
.........

11

2.2.1

String encoding management

................................
................................
................................
.....

12

2.3

Structure of the application and lifecycle

................................
................................
...........................

12

2.3.1

Activity

................................
................................
................................
................................
........

12

2.3.2

Activity Lifecycle

................................
................................
................................
.........................

13

2.3.3

Service

................................
................................
................................
................................
.........

13

2.3.4

Service lifecycle

................................
................................
................................
...........................

14

2.4

Structure of the deliverable

................................
................................
................................
................

14

2.5

Publishing an application

................................
................................
................................
....................

14

2.5.1

Preparing to Publish

................................
................................
................................
....................

14

2
.5.2

Publishing on Android Market / Google Play

................................
................................
.............

15

2.5.3

Application signature

................................
................................
................................
..................

15

2.5.4

Application update

................................
................................
................................
.....................

16

2.6

NFC Features

................................
................................
................................
................................
.......

16

2.6.1

NFC management

................................
................................
................................
.......................

16

2.6.2

New APIs

................................
................................
................................
................................
.....

16

2.6.3

API Overview

................................
................................
................................
...............................

16

2.6.4

NDEF tag read/write rules

................................
................................
................................
..........

16

2.6.5

Card Emulation

................................
................................
................................
...........................

19

2.6.5.1

API Overview

................................
................................
................................
...............................

19

2.6.5.2

Security Considerations

................................
................................
................................
...............

19

2.6.5.3

SmartCard API System Security

................................
................................
................................
...

19

2.6.5.4

Access Control

................................
................................
................................
.............................

19

2.6.6

Peer
-
to
-
Peer Data Exchange rules

................................
................................
..............................

20

2.7

NFC Application Launch

................................
................................
................................
.......................

20

2.7.1

Via User Primary Interface

................................
................................
................................
..........

20

2.7.2

Via the Card Event
(HCI) mechanism

................................
................................
..........................

20

2.7.3

Via NFC tags / external RTD

................................
................................
................................
........

21

2.8

User primary interface and Service Provider application interconnect
ion

................................
.........

22

2.8.1

Goal

................................
................................
................................
................................
.............

22

2.8.2

Metadata definition

................................
................................
................................
....................

22

2.8.3

Code sam
ples

................................
................................
................................
..............................

23

2.9

Connectivity

................................
................................
................................
................................
.........

23

2.9.1

General Requirements

................................
................................
................................
................

23


AFSCM
Android

development guidelines
v1.1

p
4
/
40


Copyright © AFSCM
2012

2.9.2

Network

................................
................................
................................
................................
......

24

2.9.3

Server Requests

................................
................................
................................
..........................

24

2.10

Security Requirements

................................
................................
................................
........................

24

2.10.1

Common security features

................................
................................
................................
......

24

2.10.2

Open Mobile API security features

................................
................................
.........................

25

2.10.3

Local protection of assets

................................
................................
................................
.......

25

2.10.4

Prohibited/Restricted resources

................................
................................
.............................

25

2.10.5

Memory usage

................................
................................
................................
........................

25

2.10.6

Al
teration of assets

................................
................................
................................
.................

25

2.10.7

Confidential assets

................................
................................
................................
..................

26

2.10.8

Protection of assets among network communications

................................
..........................

26

2.10.8.1

Prohibited transmissions

................................
................................
................................
.............

26

2.10.8.2

Personal data: restricted situations

................................
................................
............................

27

2.10.8.3

Secured transmissions

................................
................................
................................
.................

27

2.11

Protection of the Environment

................................
................................
................................
...........

28

3

S
YNTHESIS OF RULES

................................
................................
................................
............

29

4

A
PPENDICES

................................
................................
................................
......................

32

4.1.1

NFC Demo sample

................................
................................
................................
.......................

32

4.1.2

Specifying tag technologies to handle

................................
................................
........................

33

4.1.3

Using the foreground dispatch system

................................
................................
.......................

34

4.1.4

Using Foreground Dispatch with NDEF

................................
................................
.......................

36

4.1.4.1

AndroidManifest.xml

................................
................................
................................
..................

36

4.1.4.2

ForegroundNdefPush.java

................................
................................
................................
..........

37

4.1.5

Using Smart Card
-
based features

................................
................................
...............................

38

4.1.5.1

Usage pattern

................................
................................
................................
.............................

38

4.1.5.2

Sample code

................................
................................
................................
................................

38





TABLE OF FIGURES

________________________________
______________________________


Figure 1


Activity lifecycle

................................
................................
................................
...............................

13

Figure 2


Service lifecycle

................................
................................
................................
................................

14




AFSCM
Android

development guidelines
v1.1

p
5
/
40


Copyright © AFSCM
2012

1

I
NTRODUCTION

1.1

Context

The Mobile Network Operators
Bouygu
es Telecom, Orange and SFR
have founded the AFSCM
(Association Française du Sans Contact Mobile) to foster the development of mobile contactless
services.

The Service Providers
Credit Mutuel, Société Générale and Véolia have already joined the AFSCM as
ass
ociate members
.

The A
FSCM objective is to support the inception of new contactless services for mobile phone users.

In particular, AFSCM endeavors:

-

To support service providers such as banks or transit authorities in the definition and deployment
of contac
tless solutions suited for mobile subscribers to any available mobile network;

-

To specify technical guidelines for the development of mobile contactless services to ensure
seamless installation and consistent user experience;

-

To promote the benefits of the

mobile phone platform for contactless service providers, for
technology providers and for end users.

To define a mutually beneficial mobile contactless eco
-
system, AFSCM will propose a shared mobile
contactless target mark and a shared brand that will dis
tinguish those contactless services that are
available to mobile phone users.

AFSCM constituency will include all companies involved in the development of a sustainable market
for mobile contactless services such as
Service Providers
, handset makers,
smart

card manufacturers
,
Mobile Network Operators
, MVNOs. Together, AFSCM members will contribute to the definition of
innovative industry standards and best practices.

The stated objective of the AFSCM is to facilitate the development of mobile contactless se
rvices.

To this end, the founding members recognize the significance of the following success factors:

-

Virtuous eco
-
system in which all parties involved can develop a sustainable market position,

-

Efficient customer support,

-

Smooth customer experience,

-

Stat
e
-
of
-
the art application life cycle management,

-

Service portability in the event of a mobile equi
p
ment swap,

-

Service portability in the event of a
Mobile Network Operator

swap.

1.2

C
opyright license

The following document is a personal, non
-
exclusive copyright

license between you
-

the Licensee
-

and the AFSCM founding members (*), regarding the AFSCM specifications, that must be included in
any copy of said specifications.

The licensee is authorized to copy, present or communicate the AFSCM specifications on a
ny media
without having to pay any license fee under the condition that the following copyright notice be
included in any copy or any excerpt of the specifications:

« Copyright © AFSCM 2008
-
2011 (Association Française du Sans Contact Mobile ;
http://www.afscm.org/

).
All rights reserved. Terms and conditions to copy, display and communicate
these Specifications are available at
http://www.afscm.org/conditions.html

»

The licensee is NOT authorized to create or disclose modifications or abstracts of the specifications or
work derived from the specifications.


AFSCM
Android

development guidelines
v1.1

p
6
/
40


Copyright © AFSCM
2012

The specifications include detailed functional specifications, technical specifications, NFC handset
and NFC UIC
C implementation guidelines, application development guidelines (midlet and cardlet)
and SP
-
MNO interconnection guidelines.

Separate patent licenses and additional materials will be proposed to those wanting to implement
solutions compliant with the AFSCM
specifications, under licensing conditions to be defined in
separate agreements. Information for procuring such patent licenses and additional materials
documents is contained in Annex 1.

THE SPECIFICATIONS ARE SUPPLIED "AS IS" AND NEITHER THE AFSCM NOR IT
S MEMBERS ARE
COMMITTED TO ANY WARRANTY, EXPLICIT OR IMPLICIT, REGARDING THE SPECIFICATIONS, IN
PARTICULAR NO WARRANTY IS GIVEN OF QUALITY, SUITABILITY TO ANY USE WHATSOEVER, ABSENCE
OF TITLE OR RIGHTS TO THE CONTENT OF THE SPECIFICATIONS, INSURANCE THAT T
HE USE OF THE
SPECIFICATIONS WILL NOT INFRINGE INTELLECTUAL PROPRETY RIGHTS OF A THIRD PARTY SUCH AS
PATENTS, TRADE MARKS, COPYRIGHTS. NEITHER THE AFSCM NOR ITS MEMBERS SHALL BE HELD
LIABLE FOR ANY DAMAGE INCURRED IN CONNECTION TO THE USE, REPRESENTATION O
R
COMMUNICATION OF THE SPECIFICATIONS.

Neither the AFSCM name nor its trade marks shall be used under any circumstances, such as to
communicate or advertise the specifications without the prior written agreement of the AFSCM.

No rights other than the right
s described above are granted under this license and the rights granted
under this license cannot be construed as conferring, implicitly or explicitly, any rights (through a
licensing agreement or any other means) concerning AFSCM or AFSCM members inventio
ns, know
-
how or intellectual property, or any of their assets resulting from, based on or required in the
specifications.

This copyright license is subject to French law and shall be governed by and interpreted according to
French laws. The exclusive plac
e of jurisdiction shall be the Paris Court of Appeal, regardless of the
number of claims or defendants.

By downloading the AFSCM specifications, you indicate your acceptance of these terms and
conditions.

(*) : AFSCM founding members are : Bouygues Telec
om, Orange France / France Telecom, SFR

1.3

Purpose and content of this document

The purpose of this document is to provide to Service Providers some rules to develop properly their
service
Application
. A similar document is available regarding the cardlet [R3
].


The three mobile network operators within the AFSCM have agreed on a common set of rules and
recommendations regarding the design and the development of
application

appropriate for the
context of NFC services.


This document intends to refer to exist
ing documents and specifications and to highlight the topics
that are relevant regarding
application

development in these documents.



The safety of a Android application is achieved through a variety of factors mentioned throughout
this document, ranging

from the development process to the correct use of the APIs, and the
structure of the application. In addition, because these applications are intended to be embedded on
mobile handset they require particular care in the usage of the operator and device r
esources.


The next chapter

covers all the topics relevant for the development of a NFC
Application
:

-

Development process

Android applications, like any application embedded on a mobile handset, require being very
robust because resources are limited and ap
plications are difficult to update. Thus, developers

AFSCM
Android

development guidelines
v1.1

p
7
/
40


Copyright © AFSCM
2012

should be particularly concerned about specification and design phases, as well as testing
sessions.

-

Coding rules

Most principles of good standard Java practices apply to Android applications. Some of t
hem
considered as fundamental are highlighted in this chapter.

-

Structure on the application and lifecycle

The structure of Android applications and their lifecycle are specific and they are defined in
various specifications referenced in this document.

-

P
ortability considerations

This paragraph presents recommendations in order to develop application once and for all
considering the requirements for multi
-
MNO interoperability and the various capacities of the
mobile handsets.

-

NFC Controller management

Thi
s paragraph describes the interaction between the application and the NFC controller via the
NFC APIs.

-

UICC Management

This paragraph describes the interaction between the application and the UICC via the
appropriate APIs.

-

Local database management

It des
cribes the database for storing information related to all the application available on the
mobile handset.

-

Application launch

This paragraph presents the three ways to launch an application: from the
-

User Primary
Interface (which is the MNO user interf
ace), upon an event on the contactless interface or upon
reception of a SMS push.

-

User Primary Interface and Service Provider interconnection

This paragraph presents the rules in order to register properly the Service Provider application
with regard to t
he MNO user interface so that it is possible later on to launch the Service
Provider application from the MNO user interface.

-

Connectivity

This paragraph presents best practices and restrictions regarding the connection of the
application to distant serve
rs.

-

Security

This paragraph gives recommendations regarding the use of Protection Domain. It also provides
best practice rules regarding the access to sensitive data and resources.

-

Protection of the environment

This paragraph presents best practice rules t
o preserve the environment to which the mobile
handset is connected.


Throughout the document, the key points are highlighted with the following icons:


Good practice

/
R
ecommended


Forbidden


Warning

/ Mandatory


AFSCM
Android

development guidelines
v1.1

p
8
/
40


Copyright © AFSCM
2012

1.4

References

AFSCM:

The following documen
ts are available for the Service Providers:

[R1] Interface Specification
between

Telecom Operators and NFC Service Providers

[R2] NFC Applications Validation Process

[R3] Cardlet Development Guide

[R4] Guidelines for interconnection of Service Providers' a
nd MNOs' Information Systems

The AFSCM also specifies high level requirements for both UICC and mobile handset in separate
documents. These documents are only provided to the relevant suppliers on request.


Google:

http://android
-
developers.blogspot.com/2010/08/best
-
practices
-
for
-
handling
-
android.html

http://source.android.com/source/code
-
s
tyle.html

http://developer.android.com/guide/practices/design/performance.html

http://develo
per.android.com/guide/publishing/preparing.html

http://developer.android.com/guide/topics/nfc/index.html

http://developer.android.com/guide/topics/nfc/nfc.html#ext
-
type

http://developer.android.com/guide/topics/nfc/advanced
-
nfc.html


NFC Forum:

http://www.nfc
-
forum.org/specs/


1.5

Abbreviation

AFSCM

Association française du sans contact mobile

AID

Application (or Applet) IDentifier


APDU

Application Protocol Data Unit

API

Application Programming Interface

APK

Android Application
Package

ATR

Answer To Reset

BB

Base Band

BIP

Bearer Independent Protocol

CLDC

Connected Limited Device Configuration

JAD

Java Application Descriptor

JCP

Java Community Process

JSR

Java Specification Request

MIDP

Mobile Information Device Profil
e

MNO

Mobile Network Operator

NDEF

NFC Data Exchange Format


NFC

Near Field Communication

PIM

Personal Information Management (JSR75)

SE

Secure Element

SIM

Subscriber Identity Module


AFSCM
Android

development guidelines
v1.1

p
9
/
40


Copyright © AFSCM
2012

UICC

Universal Integrated Circuit Card (aka SIM)

UPI

User Prima
ry Interface

URL

Uniform Resource Locator

URI

Uniform Resource Identifier

Cardlet


Java Card

application hosted in UICC



AFSCM
Android

development guidelines
v1.1

p
10
/
40


Copyright © AFSCM
2012

2

M
ANAGEMENT RULES

2.1

Development process

The entire development process needs to be adapted to the specific aspects of Android. In part
icular,
such applications are usually small and difficult to manage, mostly because of portability
consideration.


Designing the application to minimize the device
-
specific part of the code, and integrating this issue
into the development process (e.g. usa
ge of build directives) requires special attention.

2.1.1

Specification

The most common issue is under specification.
For the development of mobile application
like
Android application or Java ME application, the specification should particularly take car of:


De
fine the usage of network resources:

The specification should design the application in order to limit the number of network
exchanges (e.g. number of request, of SMS …) and the volume of transferred data.

This specification should particularly consider th
e impact of network exchanges on availability of
the network, and consider the cost implied o the end
-
user.


Define the security assets:

The application may define its own secrets or sensitive data and could manipulate end
-
user
personal data. It is the resp
onsibility of the application to guarantee that the integrity and/or the
confidentiality of the elements are managed by the application itself or by the Android
environment. The best location for sensitive data remains the UICC or a Secure Element.


Define
the behavior of the application under abnormal situations:

Only specifying
the nominal cases may lead to leave potential vulnerabilities.


Define the usage of handset resources

Check that the needed APIs are those authorized in the current document

2.1.2

Dependen
cies in terms of device properties and features



Rule
1
:
System properties accessed within method
System.getProperty

must be hard
-
coded


The list of operating system properties and APIs features accessed by the application must be
do
cumented and transmitted to the Validation Entity for certification purposes [R2]
:


Rule
2
:
The list of all system properties accessed must be provided

(
see
System.getProperties

at
http://developer.android.com/reference/java/lang/System.html#getProperties%28%29

)


Rule
3
:
The

list of all external APIs imported by the application must be provided

(including list
of pro
prietary APIs and device
-
specific)


Rule
4
:
The list of all external APIs packaged with the application’s binary file must be provided
.

For instance, the APK file may include external classes provided by Apache, XML parsing or
cryptog
raphic libraries.

Moreover the APK file must not contain system classes (such as Open
Mobile API classes or Google Maps classes).



AFSCM
Android

development guidelines
v1.1

p
11
/
40


Copyright © AFSCM
2012

2.1.3

Usage of personal data

The list of accessed personal data and the description on
their handling must be defined.

The
followin
g rules thus apply:


Rule
5
:
The list of personal data field accessed (db used, content provider used …) must be
provided


Rule
6
:
The type (or category) of fields accessed (db used, content provider used …) must

be
provided


Rule
7
:
The list of files and folders accessed (db used, content provider used …) must be
provided


Rule
8
:
The type of files manipulated by the application must be provided


Rule
9
:
A description of usage of read/write accesses on existing personal data elements must
be provided


Rule
10
:
A description of creation/deletion of personal data elements must be provided


Rule
11
:
A descrip
tion of copying, storing and transferring personal data elements and their
destination location must be provided


More details can be found at
http://an
droid
-
developers.blogspot.com/2010/08/best
-
practices
-
for
-
handling
-
android.html
.

In France, depending on the type of data accessed, the Service Provider may have to declare this
information to the CNIL (
http://www.cnil.fr
).

2.1.4

Testing

Several elements of the mobile handset including the
Dalvik Virtual Machine

and the screen size are
specific to each mobile manufacturer and will result in discrepancies in the application behavior.

It is
strongly recommended
to test the applic
ations on each targeted device.

2.2

Coding rules

Since Android is based on Java, many style and good practice rules from Java apply to Android
applications as illustrated in the next paragraphs.

Programs are much easier to maintain when all files have a consis
tent style.

The following paragraph
is a subset of the
Android
Code Style

(
http://source.android.com/source/code
-
style.html
)

Android follows standard Java coding conventions. Android adds a
few rules:


Rule
12
:

Finalizers

should not be

used.


Rule
13
:
Imports must be fully imported
.
The
ordering of import statements is:

1. Android imports

2. Imports from third parties (com, junit, net, org)

3. java

and javax



Usage of native interface is prohibited


Rule
14
:
Usage of access qualifier is encouraged

Android applications are separated from each other by the standard Java access control
mechanism (i.e.,
sandbox model
). Thus, developers tend to neglect the strict control of the
accessibility of their classes, fields and methods, by making them all public. If this has no direct
consequence on security f
or applications, there are several reasons for which it is interesting to
deal with classes, methods or fields attributes.


Encapsulation


AFSCM
Android

development guidelines
v1.1

p
12
/
40


Copyright © AFSCM
2012

This mechanism clearly has a significant added value for the security of applications (e.g., by forcing
all accesses t
o a sensitive field to perform a proper integrity check).

Constants

Another issue with classes is the use of constants: constants make code more readable and easier to
maintain. In addition
the

usage
of
constants ha
s

a direct impact on the performance and
memory
consumption of the application.


Rule
15
:
Usage of constant and static attributes is encouraged


Exception handling rules

An application should catch all possible exceptions, including runtime exceptions, in order to avoid
the
handling of exceptions by the platform, whose default action is to display the exception trace to
the end
-
user and kill the application.

I
n order to take the proper action, it is better to use specific exceptions in catch clauses.


Rule
16
:
Exceptions have to be properly caught and handled


Rule
17
:
Exceptions

must not

be

caught and ignored without explanation.


Rule
18
:
The
generic
jav
a
.lang.
Exception

should not be the first exception caught
.



Rule
19
:
Clear f
unction separation

is encouraged

The most important feature is function separation. By clearly separating the different functions
of an application, a developer can make the application easier to implement and main
tain.


Rule
20
:
Avoid long class and methods, respect the object oriented programming philosophy

To the extent that it is feasible, methods should be kept small and focused. It is, however,
recognized that long methods are sometimes a
ppropriate, so no hard limit is placed on method
length. If a method exceeds 40 lines or so, think about whether it can be broken up without
harming the structure of the program.


Rule
21
:
Recursion is
prohibited


Rule
22
:
All switch statements must include a default rule


Rule
23
:
Writing in system output streams shall be prohibited

2.2.1

String encoding management


The service provider is responsible for the data and data format on the whole cha
in (from server to
handset). Thus she/he has to be consistent with the encoding of the strings. Data returned by the
CARDlet can be considered and managed by the service provider application as String value.


Rule
24
:

The mobile appli
cation developer must take care to the encoding format which was
used in the CARDlet and build String objects with the related format.

For instance, the JVM default encoding format can be UTF
-
8 and then String objects are built as UTF
-
8 Strings. If the dat
a returned by the CARDlet are “Latin
-
1” encoded and contains acute characters,
then UTF
-
8 String build by the service provider MIDlet won’t take in account the acute characters.

Java and Android provides the constructor
String(byte[] data,String enc)

that
should be
used to force a particular encoding format.


2.3

Structure of the application and lifecy
c
le

2.3.1

Activity

An application usually consists of multiple activities that are loosely bound to each other. Typically,
one activity in an application is specified a
s the "main" activity, which is presented to the user when

AFSCM
Android

development guidelines
v1.1

p
13
/
40


Copyright © AFSCM
2012

launching the application for the first time. Each activity can then start another activity in order to
perform different actions. Each time a new activity starts, the previous activity is stopped,

but the
system preserves the activity in a stack (the "back stack"). When a new activity starts, it is pushed
onto the back stack and takes user focus. The back stack abides to the basic "last in, first out" queue
mechanism, so, when the user is done with

the current activity and presses the BACK key, it is
popped from the stack (and destroyed) and the previous activity resumes.

2.3.2

Activity
Lifecycle


Figure
1



Activity lifecycle

2.3.3

Service

A Service is an application component that ca
n perform long
-
running operations in the background
and does not provide a user interface. Another application component can start a service and it will
continue to run in the background even if the user switches to another application. Additionally, a
com
ponent can bind to a service to interact with it and even perform
i
nter
-
p
rocess
c
ommunication
(IPC). For example, a service might handle network transactions, play music, perform file I/O, or
interact with a content provider, all from the background.


AFSCM
Android

development guidelines
v1.1

p
14
/
40


Copyright © AFSCM
2012

2.3.4

Servi
ce lifecycle


Figure
2



Service lifecycle

2.4

Structure of the deliverable

An Android application is packaged as an APK file format. A .apk file extension denotes an Android
Package (APK) file. This file format is used for the dist
ribution and installation of bundled
components onto the Android mobile device platform.

T
he APK file must not contain system classes
,
as defined in
Rule
4
).

An APK file is an archive that usually contains the following folders:


M
ETA
-
INF


res

and files:


AndroidManifest.xml


classes.dex


resources.arsc

2.5

Publishing an application

2.5.1

Preparing to Publish

Publishing an application means testing it, packaging it appropriately, and making it available to users
of Android
-
powered mobile devi
ces. This paragraph highlights the significant checkpoints for
preparing an application for a release.

Before considering an application ready for release:


Test the application extensively on
several

actual device
s


AFSCM
Android

development guidelines
v1.1

p
15
/
40


Copyright © AFSCM
2012


Consider adding an End User License Agree
ment in the application


Consider adding licensing support


Specify an icon and label in the application's manifest


Turn off logging and debugging and clean up data/files

Before doing the final compile of the application
:


Version the application


Obtain a sui
table cryptographic key


Register for a Maps API Key, if the application is using MapView elements

Compile the application
.

After compiling the application
:


Sign the application


Test the signed application

2.5.2

Publishing on Android Market

/ Google Play


To publ
ish an application on Android Market

/ Google Play
, the service provider first need to register
with the service using a Google account and agree to the terms of service. Then the application can
be uploaded to the service and published when ready. Once pu
blished, users can see the application,
download it, and rate it using the Market application installed on their Android
-
powered devices.

To publish an application on Android Market

/ Google Play
, it has to meet the requirements listed
below, which are enf
orced by the Market server when the application is uploaded.

Requirements enforced by the Android Market
/ Google Play

server:


The application must be signed with a cryptographic private key whose validity period ends after
22 October 2033
.


The application
must define both an
android:versionCode

and an
android:versionName

attribute in the
<manifest>

element of its manifest. The server
uses the
android:versionCode

as the basis for identifying the application internally and
handling updates, and it displays th
e
android:versionName

to users as the application's
version.


The application must define both an
android:icon

and an
android:label

attribute in
the

<application>
element of its manifest.


The service provider shall take care

that the application
s

will be sh
own

to the user only if the
device is NFC ready.


The new version of the application has to match the previous version regarding NFC capabilities
and backward compatibility

2.5.3

Application signature

An application can only be signed once. To allow access to the

UICC application, this signature is the
signature of the MNO.

The format used for the signature can be either MD5 or SHA1, depending on
the Service Provider’s needs

(by default, the SHA1 format will be provided by the MNOs)
.



Rule
25
:

Since the package identifier must be unique, the Service Provider must publish as many
variants of applications as there are MNO supported.


Rule
26
:

Thus, caution is advised as to the application name that
should include the MNO n
ame
in order to guide the end user the correct application.


Note: this shortcoming is being addressed but is unfortunately currently unavoidable.


AFSCM
Android

development guidelines
v1.1

p
16
/
40


Copyright © AFSCM
2012

2.5.4

Application update



Rule
27
:

When publishing an update to its application, the SP shou
ld increment the
android:versionCode

property
.


2.6

NFC
Fea
t
ures

2.6.1

NFC management

The NFC controller is the dedicated chipset (and its antenna) which enables the contactless
communication. Three modes are supported:


Card/Tag writing/reading


Card emulation


Peer
-
t
o
-
peer

By using
the Android NFC
APIs, developers can:


Read/write passive contactless device


Exchange APDU with (external) contactless smart card.

Furthermore, the NFC with Android implements the “Push” mechanism. “Push” is a very powerful
concept and typic
ally refers to the mechanism or ability to receive and act on information
asynchronously, as information becomes available, instead of forcing the application to use
synchronous polling techniques that increase resource use or latency.

2.6.2

New APIs

Near
-
field
Communication or NFC is a standard defined by the NFC Forum. NFC Data Exchange
Format (NDEF) defines a common data format between NFC
-
compliant devices and tags.
From
Android Gingerbread (2.3
.3

or 2.3.4
, API Level
10
), it is possible to use NFC functionali
ty, allowing
applications to read NDEF message in NFC tags. A "tag" may actually be another device that appears
as a tag.



Rule
28
:
Use of Android Gingerbread 2.3, API Level 9 is obsolete and is discouraged

2.6.3

API Overview

A summary of
the classes can be found at:

http://developer.android.com/reference/android/nfc/package
-
summary.html

2.6.4

NDEF tag read/write
rules

Declaring Android Manifest elements


Rule

29
:
In order to access

a device's NFC hardware and properly handle NFC intents, the

following

items
must

be declared
in the
AndroidManifest.xml

file:

1.

The NFC
<uses
-
permission>

element to access the NFC hardware:

<uses
-
permission

and
roid:name
=
"android.permission.NFC"

/>

2.

The minimum SDK version that the application can support. API level
10

(level 9 is obsolete)
only
supports limited tag dispatch via
ACTION_TAG_DISCOVERED
, and only gives access to NDEF
messages via the
EXTRA_NDEF_MESSA
GES

extra. No other tag properties or I/O operations are
accessible. Use API level 10 which includes comprehensive reader/writer support.

<uses
-
sdk

android:minSdkVersion="10"/>

3.

The uses
-
feature element so that the application can show up in the Android Mar
ket

/ Google
Play

for devices that have NFC hardware:

<uses
-
feature

android:name="android.hardware.nfc"

android:required="true"

/>


AFSCM
Android

development guidelines
v1.1

p
17
/
40


Copyright © AFSCM
2012

4.

The NFC intent filter to tell the Android system the Activity can handle NFC data. Specify one or
more of these three intent
s

filters

in the activity
:

<intent
-
filter>


<action android:name="android.nfc.action.NDEF_DISCOVERED"/>


<data android:mimeType="mime/type" />

</intent
-
filter>

<intent
-
filter>


<action android:name="android.nfc.action.TECH_DISCOVERED"/>


<meta
-
data android:
name="android.nfc.action.TECH_DISCOVERED"
android:resource="@xml/nfc_tech_filter.xml" />

</intent
-
filter>

<intent
-
filter>


<action android:name="android.nfc.action.TAG_DISCOVERED"/>

</intent
-
filter>


The three intent filters are prioritized and behave in s
pecific ways. Declare only the ones that
the
Activity needs to handle.


The Tag Dispatch System

When an Android device scans an NFC tag, the desired behavior is to have the most appropriate
Activity handle the intent without asking the user what applicatio
n to use. Because devices scan NFC
tags at a very short range, it is likely that making users manually select an Activity forces them to
move the device away from the tag and break the connection.


Rule
30
:
Developer should develop t
he Activity to only handle the NFC tags that the Activity
cares about to prevent the Activity Chooser from appearing.


Android provides two systems to help the developer correctly identify an NFC tag that the Activity
should handle:


the Intent dispatch sy
stem and


the foreground Activity dispatch system.


The intent dispatch system

The intent dispatch system

checks the intent filters of all the Activities along with the types of data
that the Activities support to find the best Activity that can handle the

NFC tag. If multiple Activities
specify the same intent filter and data to handle, then the Activity Chooser is presented to the user
as a last resort.

The intent dispatch system specifies three intents that each has a priority
:


android.nfc.action.NDEF_DI
SCOVERED


android.nfc.action.TECH_DISCOVERED


android.nfc.action.TAG_DISCOVERED

The intents that start when a device scans a tag depend on the type of tag scanned. In general, the
intents are started in the following manner:


android.nfc.action.NDEF_DISCOVER
ED
: This intent starts when a tag that contains an
NDEF payload is scanned. This is the highest priority intent. The Android system does not let
the
developer
specify this intent generically to handle all data types.



AFSCM
Android

development guidelines
v1.1

p
18
/
40


Copyright © AFSCM
2012


Rule
31
:
The de
veloper must specify
<data>

elements in the
AndroidManifest.xml

along
with this intent to correctly handle NFC tags that start this intent.

For
instance
, to handle a NDEF_DISCOVERED intent that contains plain text, specify the following
filter in your Andr
oidManifest.xml file:

<intent
-
filter>


<action android:name="android.nfc.action.NDEF_DISCOVERED"/>


<data android:mimeType="text/plain" />

</intent
-
filter>

If the
NDEF_DISCOVERED

intent is started, the
TECH_DISCOVERED

and
TAG_DISCOVERED

intents are n
ot started.

This intent does not start if an unknown tag is scanned or if the tag does not contain an NDEF
payload.


android.nfc.action.TECH_DISCOVERED
: If the
NDEF_DISCOVERED

intent does not start
or is not filtered by any Activity on the device, this in
tent starts if the tag is known. The
TECH_DISCOVERED

intent requires that the developer specifies the technologies that he/she
wants to support in an XML resource file.


android.nfc.action.TAG_DISCOVERED
: This intent starts if no Activities handle the
NDEF
_DISCOVERED

and
TECH_DISCOVERED

intents or if the tag that is scanned is unknown.



Rule
32
:
I
f
an
Activity declares the
android.nfc.action.TECH_DISCOVERED

intent in
your
AndroidManifest.xml

file, the developer must create an XML reso
urce file that
specifies the technologies that the Activity supports within a tech
-
list set. The Activity is
considered a match if a tech
-
list set is a subset of the technologies that are supported by the tag,
which the developer can obtain by calling
getT
echList()
.

An example is available at the
paragraph “Specifying tag technologies to handle” in the Appendixes
.


The
foreground

dispatch system

The foreground dispatch system

allows an Activity application to override the intent dispatch system
and have pri
ority when an NFC tag is scanned. The Activity handling the request must be running in
the foreground of the device. When an NFC tag is scanned and matches the intent and data type that
the foreground dispatch Activity defines, the intent is immediately se
nt to the Activity even if
another Activity can handle the intent. If the Activity cannot handle the intent, the foreground
dispatch system falls back to the intent dispatch system.

The foreground dispatch system

allows an Activity to intercept an intent a
nd claim priority over
other Activities that handle the same intent. The system is easy to use and involves constructing a
few data structures for the Android system to be able to send the appropriate intents to your
application.



Rule
33
:
When using the foreground dispatch system, the developer
must

define the MIME that
will be handled. Only the ones needed have to be specified. An example is available at the
paragraph “Using the foreground dispatch system” in the Appendixes.


More d
etails about
Working with Data on NFC Tags
,
Reading an NFC Tag
,
Writing to an NFC Tag

are
available
at:


http://developer.android.com/guide/topics/nfc/nfc.html
,


http://developer.android.com/guide/topics/nfc/advanced
-
nfc.html
,


AFSCM
Android

development guidelines
v1.1

p
19
/
40


Copyright © AFSCM
2012

2.6.5

Card Emulation

For more informa
tion about the architecture of Smartcard API refer to the site:
http://code.google.com/p/seek
-
for
-
android/wiki/SmartcardAPI
. The Smartcard APIs V2 are base
d

on
the SIM Alliance sp
ecification release 1.
2
.


Rule
34
:
[NFC Push
-

Card Emulation] If dynamic registration is performed,
the
registration
string

has to be hard
-
coded. Else it has to be in the manifest.

2.6.5.1

API Overview

The SIM Alliance specification can be f
ound at the following URL

(regist
ration required

to get the
specification

freely
)
:
http://simalliance.org/en?t=/documentManager/
sfdoc.file.supply&e=UTF
-
8&i=1185787014303&l=0&fileID=1300467720550
.

The API documentation

can be found at the following URL:
http://seek
-
for
-
android.googlecode.com/svn/trunk/d
oc/index.html
.

2.6.5.2

Security
C
onsiderations

At install
ation

time, the user is asked whether or not the application should receive access to his or
her secure element.


Access to the lower layer components such as the secure element specific terminal
implementat
ion will be protected with the standard Android mechanisms.


The whole Android security scheme is based on standard UID/GID check; therefore applications
with root access can overcome the security mechanism. For example, it is possible that a root
user repl
aces APKs or native system services with modified versions that contain tracers or
hooks for other applications. This means that the security concept of the Smartcard API can be
broken on rooted phones but this is not an issue of the API design but a gener
al issue on Linux
based systems where root can do everything.

2.6.5.3

SmartCard API System Security

The security considerations for the SmartCard API can be found at:

http://code.google
.com/p/seek
-
for
-
android/wiki/SecurityConcept

The SmartCard API system security discussion explains the mechanism needed so client applications
cannot overcome the SmartCard API interface by using the lower level components directly.

In order to protect th
e low level components, the SmartCard API remote process is installed and
registered with a unique UID/GID: smartcard

All low level components and methods check for the caller UID and
-

if not smartcard
-

throw an
exception.

2.6.5.4

Access Control

To access the Sm
art Card through the APIs, the application file (APK) has to be signed
. The
way to
sign an application depends

on the technologies chosen by the handset

makers
. There are currently
two technologies:


One based on the PKCS#15 certificates;
it’s based on the
signature of the mobile application and
is enforced when accessing the transport layer. Certificates are stored in the SE. According
permissions are stored in the SE or in the signed application itself.


The other one is based on the Seek
-
For
-
Android mechan
ism: “
The access control scheme of the
SmartCard API is a protection mechanism that ensures that only allowed (or certified) Android
applications are able to access specific Java Card applets depending on the APK certificate

.

The implementation relies on
an extension of the handset integration in combination with
an

access
control application running on the Secure Element.



AFSCM
Android

development guidelines
v1.1

p
20
/
40


Copyright © AFSCM
2012

The application must follow the following rules:


Rule
35
:
The use of the method
basicChannel

is prohibited


Rule

36
:
[Open Mobile API]
The c
onnection
string
of the
openLogicalChannel

function
has
to be hard
-
coded


Rule
37
:
[Open Mobile API] The application only accesses its own cardlets

2.6.6

Peer
-
to
-
Peer Data Exchange

rules

An
droid Beam allows simple peer
-
to
-
peer data exchange between two Android
-
powered devices.

The application that wants to beam data to another device must be in the foreground and the device
receiving the data must not be locked. When the beaming device comes

in close enough contact with
a receiving device, the beaming device displays the "Touch to Beam" UI. The user can then choose
whether or not to beam the message to the receiving device.

To use Android Beam, the following general guidelines must be met:


Ru
le
38
:
The activity that is beaming the data must be in the foreground. Both devices must
have their screens unlocked.


Rule
39
:
must encapsulate the data that
he/she

is

beaming in an NdefMessage object.


Rule
40
:
The NFC device that is receiving the beamed data must support the com.android.npp
NDEF push protocol or NFC Forum's SNEP (Simple NDEF Exchange Protocol). The
com.android.npp protocol is required for devices on API level 9 (Android
2.3) to API level 13
(Android 3.2). com.android.npp and SNEP are both required on API level 14 (Android 4.0) and
later.

If
the

activity enables Android Beam and is in the foreground, the standard intent dispatch system is
disabled. However, if
the

activity

also enables foreground dispatching, then it can still scan tags that
match the intent filters set in the foreground dispatching
.

More details about Peer
-
to
-
Peer are available at:

http://developer.android.com/guide/topics/nfc/nfc.html#p2p

2.7

NFC Application

Launch

2.7.1

Via User Primary Interface

The Service Provider MMI (Android NFC Application) can be launched from the MNO MMI (UPI).

UPI will produce a call to
startActivity (Intent inten
t)

method where the intent will be
created
using UPI context and Service Provider defined activity name in the Service Provider manifest
file.

2.7.2

Via
the Card Event (HCI) mechanism

The
card event mechanism

enables applications to set themselves up to be launc
hed automatically,
without user initiation.

This kind of notifications is emitted by cardlets within the UICC (e.g. at the
end of the NFC transactions
.


Rule
41
:
When

using Card Event mechanism

in order to
properly handle NFC events,
the
following items have to be declared in the
AndroidManifest.xml

file:

1.

M
inimum SDK version 10 (Android 2.3.4) must be used

2.

The NFC
<uses
-
permission>

element to use the NFC Event:

<uses
-
permission android:name="android.permission.NFC" />

<uses
-
permission
android:name="android.permission.NFC_TRANSACTION"/>

3.

The NFC intent filter to tell the Android system the Activity can handle NFC
Event
. Specify one or
more of these intent
s

filters

in the activity
:

<activity


android:name=".EventReceiver"


AFSCM
Android

development guidelines
v1.1

p
21
/
40


Copyright © AFSCM
2012


android:la
bel="@string/activity_name"


android:launchMode="singleTask"


android:screenOrientation="portrait">


<intent
-
filter>


<action android:name="android.nfc.action.TRANSACTION_DETECTED"></action>


<category android:name="android.intent.ca
tegory.DEFAULT"></category>


<data


android:scheme="nfc"


android:host="secure"



android:port="0"


android:path="/0102030405060708090000"/> <!
--

AID
--
>


</intent
-
filter>

</activity>


Note
s
:


The hexad
ecimal letters [a
-
f] must be lower
-
cases. Thus a correct AID will be
a00101ae024678 while 01B101AE024678 will not work.


If two applications register the same AID, one with upper
-
cases and the other with lower
-
cases, only the application
with a lower
-
cases
AID
will be launched upon the HCI event


If two applications correctly register the same AID, with lower
-
cases, the only application
launched will be the one that has been installed first. No error message will be shown to the
user upon installation of the
second application.


4.

The application has to be launched in single task mode to avoid to start a new activity after a NFC
transaction if it has been already launched
:

<activity android:name=".EventReceiver" android:label="@string/app_name"
android:launchMod
e="singleTask"

android:screenOrientation="portrait">

Moreover the method
onNewIntent(Intent intent)

has to be overridden to allow the
retrieval of new intents after the NFC Transaction if the application has been already launched.
The TAP
-
PIN
-
TAP scenario
is an example of use case.

5.

The uses
-
feature element so that the application can show up in the Android Market

/ Google
Play

for devices that have NFC hardware:

<uses
-
feature android:name="android.hardware.nfc" android:required="true" />

2.7.3

Via NFC tags / exte
rnal RTD

The Service Provider MMI (Android NFC Appli
cation) can be launched
by reading
a

NFC tag

with a
n

external
RTD content

(
The External Type Name is meant for organizations that wish to self
-
allocate a
name space to be

used for their own purposes
)
.
It
look like this:

urn:nfc:ext:example.com:externalType

.

The application
will be launched
once the tag has been
read by the device.


Rule
42
:
When using
this

mechanism

in order to
properly handle NFC
external RTD

tags
, the
following i
tems have to be declared in the
AndroidManifest.xml

file:

1.

M
inimum SDK version 10 (Android 2.3.
6
) must be used

2.

The NFC
<uses
-
permission>

element to use the NFC Event:

<uses
-
permission android:name="android.permission.NFC" />

3.

The NFC intent filter to tell th
e Android system the Activity can handle NFC
Event
. Specify one or
more of these intent
s

filters

in the activity
:

<intent
-
filter>


<action android:name="android.nfc.action.NDEF_DISCOVERED" />


<category android:name="android.intent.category.DEFAULT"
/>


AFSCM
Android

development guidelines
v1.1

p
22
/
40


Copyright © AFSCM
2012


<data android:scheme="vnd.android.nfc"


android:host="ext"


android:pathPrefix="/example.com:externalType"/>

</intent
-
filter>


Tip:
The developer SHOULD u
se TNF_EXTERNAL_TYPE for more generic NFC tag deployments to better
support both
Android
-
powered and non
-
Android
-
powered devices.


Note: If several applications are registered to be launched on the same NDEF external RTD content,
the system activity “
TechListChooserActivity

(inherited from ResolverActivity)” appears to allow the
user t
o choose the application to be launched.Thus
, the
Foreground Dispatch System

must be used if
the application
needs
to claim the
priority over other activities that handle the same intent
.

BUT if
there is more than one application using this Foreground Disp
atch for the same external RTD
content, Android will launch

the “
TechListChooserActivity
”.
For more information, see reference:


http://developer.android.com/guide/topics/nfc/nf
c.html#ext
-
type


http://developer.android.com/guide/topics/nfc/advanced
-
nfc.html#foreground
-
dispatch

A full example to use the foreground dispatch can be f
ound

appendices 4.1.4.

2.8

User primary interface and Service Provider
application
interconnection

2.8.1

Goal

As announced in the introduction

chapter, the present document should also list the programming
requirements allowing service providers to develop Applicati
ons maximizing Application portability
across MNO environments
.

2.8.2

Metadata definition

The UPI will collect the application’s information from its
AndroidManifest.xml file.



Rule
43
:
The
following metadata
must

be declared in the
Androi
dManifest.xml

file

to
ensure
UPI
interconnection
:


android:label
: ASCII. This is the name the UPI will display to users in the UPI main screen.


android:versionName
: ASCII with the following format: x.x.x (x being an integer such that
0<=x<=99)
;


android:icon
: PNG (transparent) file format.
A
pplication must define three
sizes

of icons
(one for low
density screen, one for medium density and one for high density)

and may
define another size for extra
-
high density screens
:



ldpi: 36*36 pixels

(mandatory)
;



mdpi: 4
8*48 px

(mandatory)
;



hdpi: 72*72 px

(mandatory);



x
hdpi: 96*96 px

(optional).



See
http://developer.android.com/guide/topics/manifest/activity
-
element.html#icon

fo
r more information.


NFC
-
App
-
Name
: ASCII / Max 10 characters.
[A
-
Za
-
z0
-
9]

use of the dash character is allowed
;


NFC
-
App
-
Vendor
: ASCII /
Max 10 characters.
[A
-
Za
-
z0
-
9]
;


NFC
-
Service
-
Nb
: integer; Represents the number of services


For each service x (where x is

an integer and 0 < x <
=

NFC
-
Service
-
Nb), the following
metadata must be included


AFSCM
Android

development guidelines
v1.1

p
23
/
40


Copyright © AFSCM
2012



NFC
-
Service
-
Label
-
x
: ASCII / Max 10 characters. [A
-
Za
-
z0
-
9;dash;dot;space];
This is the name of the service, which the UPI will display to users in the UPI
main screen



NFC
-
Se
rvice
-
AID
-
x
:

concatenation of the “aid:” string and an
hexa
decimal

string representing
the

long AID
s

of the cardlet application
s

that the APK is
using.
x
is the number of the cardlet (e.g. 1, 2, …)
;

The length has be
4+
10 up
to
4+
32: e.g.
aid:
a001020304050
607




NFC
-
Service
-
Type
-
x
: 1 byte.


0x00: Other


0x01: Loyalty


0x02: Payment


0x03: Transport


0x04
-
>0xFF: TBD



Rule
44
:
UPI interconnection metadata

must be contained in the application that serves as the
main entry into the app (
android.
intent.action.MAIN
).


Rule
45
:
NFC
-
App
-
Name

and
NFC
-
app
-
Vendor

must

be constant: no dymanic value such as

@string/app_name
”.


2.8.3

Code samples


-

Man
i
f
est tag attribute: android:versionName

<manifest xmlns:android=
http://schemas.android.com/apk/res/android


android:versionCode="X"


android:versionName="
x.x.x
"
>

<
/manifest>

-

Application tag attibutes: android:icon and android:label

and Application tag meta data.

<application android:i
con="
@drawable/icon
"


android:label="
@string/app_name
">



<meta
-
data android:name="NFC
-
App
-
Name" android:value="
abcd
"></meta
-
data>


<meta
-
data android:name="NFC
-
App
-
Vendor" android:value="
efgh
"></meta
-
data>


<meta
-
data android:name="NFC
-
Service
-
Nb"
android:value="
1
"></meta
-
data>


<meta
-
data android:name="NFC
-
Service
-
Label
-
1"
android:value="
ijkl
"></meta
-
data>


<meta
-
data android:name="NFC
-
Service
-
AID
-
1"
android:value="
aid:
0102030405060708090000
"></meta
-
data>


<meta
-
data android:name="NFC
-
Service
-
Type
-
1
"
android:value="
mnop
"></meta
-
data>


</application>


2.9

Connectivity

Android/Google

specification defines a
Connectivity

Framework (
Webkit and Apache HTTP librairies
)
which gives to the applications the possibility to establish data connections with distant
server.

2.9.1

General Requirements

Many APIs use URLs to refer to resources. Beyond the connection API
s
, URLs are also used in media
players, and elsewhere.

It is therefore very important to determine properties about URLs, because they are used by the
verificat
ion process to determine which protocols


connections


resources are used by the

AFSCM
Android

development guidelines
v1.1

p
24
/
40


Copyright © AFSCM
2012

application
. This information can actually be inferred if the URLs comply with simple constraints such
as specifying a determined scheme.


Rule
46
:
The

application must only use URLs in which the protocol and destination host are
determined.


Rule
47
:

URLs must not be dynamically built (the application must use fixed host strings)
.

2.9.2

Network


Rule
48
: The applica
tion must only use HTTP and HTTPS network connections.

In particular, the
following low
-
level protocols are prohibited: datagram, socket, ssl and tcpobex.

The verification process consists in checking that among all the opened network connections (or
strea
ms), the application only uses http and https connections.


Rule
49
:
The application should not open connections to numerical IP addresses.

This rule simply consists in forbidding the usage of numerical IP addresses to meet both
porta
bility and security requirements.


Rule
50
:
The application should not open connections to local host.

As previously mentioned, applications are not allowed to share

data

and services
with other
applications. Opening a connection to
l
ocalhost

or to
127.0.0.1

is therefore strictly
prohibited since it can be used to get out of the application’s sandbox, by performing direct
exchanges with native code on the platform.

2.9.3

Server
Requests

The
Android
specification defines a method allowing
app
lications
to request that the device handles
an indicated URL.


Rule
51
:
File downloading is forbidden, except auto
-
update use case

The use of requests should be limited to Web content browsing. Applications must therefore not
use HT
TP requests for downloading files, except for the specific purpose of initiating the update
of the application.

This means that download requests should be limited to URLs pointing to the newest version of
this application and
this must be done through th
e package manager of through the Android
market

/ Google Play


Rule
52
:
The application should only use constant or determined phone numbers

This is particularly important to detect costly calls to premium or international numbers.

2.10

Se
curity
Requirements

2.10.1

Common security features

Android has its own security and permission mechanism. See:
http://developer.android.com/guide/topics/security/security.html




Ru
le
53
:
Regarding the mandatory
Android

and
Open Mobile

API
s
, the following permissions
should

be requested by SP
applications
:


Permissions needed to use NFC capabilities (tag read, peer
-
to
-
peer):


android.permission.NFC
,


Permissions n
eeded to launch application through card emulation (NFC Push):


android.permission.NFC_TRANSACTION


Permissions needed to access Smart Card through Open Mobile API:


android.permission.SMARTCARD

(for Seek
-
for
-
Android 2.2.1)


org.simalliance.openmobileapi.SMART
CARD

(for Seek
-
for
-
Android
2.2.2
and later


new permission
)


AFSCM
Android

development guidelines
v1.1

p
25
/
40


Copyright © AFSCM
2012


Rule
54
:
Because some handset already on the market can implement either seek
-
for
-
android
2.2.1 or 2.2.2 and to ensure a retro compatibility, it is recommended to add both
android.permission.SMARTCARD

and

org.simalliance.openmobileapi.SMARTCARD

permissions
)


Rule
55
: In order to make the application installable and visible on the market only to handsets
supporting the Open Mobile APIs, the Android Manif
est.xml must contain the following line:

<uses
-
library android:name="org.simalliance.openmobileapi"
android:required="true" />
.
The
uses
-
library
tag must

in
the

<application>

tag
and only in this tag.

More details can be found at: http://code.google.com/p/
seek
-
for
-
android/wiki/UsingSmartCardAPI

Whatever the security level reached by the application,
Service Providers
are strongly encouraged to
constantly inform the end
-
user of the nature of the operations being processed.

2.10.2

Open Mobile API

security

features

T
he SmartCard API uses the Android permission scheme to protect access to secure elements.
Therefore it defines permission
s

(
android.permission.SMARTCARD

or
org.simalliance.openmobileapi.SMARTCARD
)
that a client application must request in its
manifest in o
rder to obtain access to the API.

Additional security features exist specifically for the
Open Mobile
API. An
access control model is
designed to achieve the following security objectives:


Protect UICC from malicious applications,


Support UICC to specify a

fine
-
grained access control policy within the limitations of the
platform,


Allow a
n

application to select an UICC object (for example, a smart card cardlet application) for
temporary exclusive usage,


Safeguard PINs from improper usage by the application.

2.10.3

Local protection of assets

The application is responsible
for

the protection of the local assets during their manipulation.

Depending of the type of manipulated asset, the application should take appropriate security
measures to ensure its protection.

2.10.4

Proh
ibited/Restricted resources


Rule
56
:
The application
must
not access any
non
-
public
resources

of other applications
.


Rule
57
:
The application
must

not access
the user’s MSISDN
.

2.10.5

Memory usage

Applications are int
ended to be executed on an embedded environment, with limited resource
capabilities, in particular memory.

The API inherits from standard Java the method
System.gc

that allows applications to explicitly
initiate
t
he Garbage Collection process.

However, t
he

behavior of the Garbage Collector varies
significantly from one device to another, and it can take a long time to proceed. In addition, there is
no guarantee the requested collection operation is immediately performed.


Rule
58
:
Expl
icit usage of garbage collection is strongly discouraged.

2.10.6

Alteration of assets

Applications are not intended to alter or corrupt the data or files managed by the platform, mostly
because these data are shared with other applications and this could lead to
severe functional issues.


AFSCM
Android

development guidelines
v1.1

p
26
/
40


Copyright © AFSCM
2012

Then, the application must particularly consider the following requirements.


Rule
59
:
The application must not alter personal information

without user consent

For security reason, applications are not suppos
ed to alter personal data. The objective is here
to ensure that applications are only able to add new contacts or events using the
Contacts
Content Provider
. In other words, applications are not able to modify or remove existing PIM
entries
.


Rule
60
:
The application verifies the consistency of its
database

This rule simply recommends applications to perform format verification on the content of the
database

while inserting or extracting data. This may be useful to detect a record corr
uption.


Rule
61
:
The application should p
erform
verification to preserve system integrity

The application should make significant effort to preserve the integrity of the file system: private
user or system folders shall never be acce
ssed or altered.

The application must implement safety verifications that restrict destination folders and that
ensure only well
-
identified files are modified, and always after appropriate end
-
user
confirmation for files that were not initially created by
the application.


Rule
62
:
The application should

preserve RFID tags integrity

The application should make significant effort to preserve the integrity of the RFID tags it writes
(
e.g.
, when writing NDEF tags).

The application must im
plement safety verifications that restrict records and offsets being
modified.


Rule
63
:
The application verifies the consistency of its files

This rule simply recommends applications to perform format verification on the content of t
heir
own files while inserting or extracting data. This may be useful to detect a file’s corruption.

2.10.7

Confidential assets

The application may be responsible to manage confidential assets. These assets are end
-
user’s
secrets (
e.g.
, service logins and passwor
ds) or application
-
own asset (
e.g.
, activation or encryption
keys).


Rule
64
:
The application does not define default passwords for accessing its services.

Most end
-
users never change the password attributed by the service. Thus, defi
ning default
password exposes users to identity theft attacks.


Rule
65
:
Application’s secrets are not hard coded plaintext in the code.

On some devices and some provisioning servers, the
APK
file is not protected against disclosure.
Thus, an attacker could disassemble the application’s code and retrieve any secret value it
contains.


Rule
66
:
Secrets are not stored as plaintext.

Developers should particularly consider the issue about persistent storage, as files
and (on some
device) record stores are exposed to data disclosure.

As a consequence, the application must implement encryption features to protect these secrets.


Rule
67
:
Avoid decrypting secrets for comparison.

When possible, the ap
plication should prefer to perform the verification of secrets on encrypted
values. This will prevent the application from involuntary storing the plaintext secret value.

2.10.8

Protection of assets among network communications

Most of the assets manipulated by t
he application are not intended to be transmitted to any remote
entity. This is the purpose of this section which defines the security guidelines accordingly.

2.10.8.1

Prohibited transmissions

In order to preserve end user's privacy, the applications are not allowe
d to transmit to remote
entities some categories of data.


Rule
68
:
The application does not send Operator and third party data.


AFSCM
Android

development guidelines
v1.1

p
27
/
40


Copyright © AFSCM
2012

Usage of Operator data should be restricted to local computations.


Rule
69
:
The a
pplication does not send device localization data

(without end user approval)
.

Usage of localization data should be restricted to local localization computations. If sending
localization data is required, the protection of end
-
user privacy rights must be e
nsured on
servers.


Rule
70
:

The application does not send identification data

(without end user approval)
.

It seems quite natural to forbid transmission of device network identification information as it is
also strictly forbidden to

manipulate them.


Rule
71
:
The application does not send device configuration data

(without end user approval)
.

The properties are restricted to local computations, as they could be used for illegal statistics or
commercial purposes.

They should therefore not be transmitted to any remote entity.

2.10.8.2

Personal data: restricted situations

There are some very specific guidelines regarding the security of personal data.

In nominal situations they are not intended to be transmitted to any remot
e entities. For instance,
service provider must not

be

able to collect all the contacts of the end
-
user.

There are some exceptional situations, not recommended at all, where the application requires be
ing

able to transmit some personal data. This should be

strictly limited to data storage (backup) services,
and personal data stored on remote servers must not be exploitable by any entity except the local
application
, as stated in the security requirement

below
:


Rule
72
:
The application

ensures personal data cannot be exploited remotely

(without end user
approval)
.

The exploitation of personal data is restricted to local computations and exchanging them is
strongly discouraged. When some personal data are exchanged for backup purposes, t
he
application must

ensure these data cannot be interpreted remotely, by implementing a
dedicated cryptographic mechanism. Data are transmitted enciphered with a key solely known
by the end
-
user or the local agent.

2.10.8.3

Secured transmissions

For data that could

be exchanged between entities, some of them may require the implementation
of specific security mechanisms, especially to prevent social
-
engineering attacks.


Rule
73
:
The application implements mutual authentication mechanisms.

Ther
e are several situations where applications are intended to authenticate the destination
server of a service. This is particularly important when the server provides some content which
could have an impact on the security of the application (
e.g.
, requesti
ng the local agent to
perform costly operations) or the device (
e.g.
, download of malicious applications).

In all of the above mentioned situations, the Java framework provides for instance features to
initiate HTTPS connections and to verify server creden
tials.


Rule
74
:
The design of the service prevents replay attacks.

This is the only server
-
oriented security requirement mentioned in this document as it has some
impact on the implementation of the local agent. In particular request
s to remote servers shall
be protected against replay attacks, especially authentication requests, as it should not be
possible for an attacker to illegally authenticate on servers.


Rule
75
:
The application uses encrypted communicati
ons.

The application can manipulate its own secrets (
e.g.
, activation key) or some of the end
-
user
(
e.g.
, logins, password).This rule simply mandates that when private data are exchanged, they
are not in plaintext.

This is particularly recommended for end
-
user remote authentication procedures (e.g.,
password

submission).


Rule
76
:
The application must handle the cases when the cardlet is not present.


AFSCM
Android

development guidelines
v1.1

p
28
/
40


Copyright © AFSCM
2012


2.11

Protection of the
E
nvironment

The security of mobile applications does not only conce
rn local features, but also requires
consider
ing

the global environment. Mobile handset are mobile items in a wide network connecting
personal computers, other handsets, other devices (headphone, GPS receiver), through several
operating systems and protoco
ls.

Thus,
the
application
s

are not only the direct target of the attacks: they could be used as
communication interfaces, for instance to propagate a malware program.

This is also particularly important to
focus
on some security guidelines defining how the

application
should behave in such connected environment.


Rule
77
:
The application shall not send any executable program to remote entities.

A mobile application must not be a vector to propagate malware programs among the network.
T
he applications that send some files are intended to verify these files are not executable among
the following non
-
exhaustive list of extensions:
.
exe, .cab, .msi, .sis, .jar,

.bat, .sh, .pif
.


Rule
78
:
Executable code in SMS/MMS bina
ry messages is forbidden.

This rule is an extension of the previous requirement, to precise that is also applies to SMS or
MMS binary messages: executable code must be prohibited in the body of these messages.


Rule
79
:
The applicatio
n shall not intensively use network resources.

In particular, the application shall not massively send emails or any kind of data as:


It implies a cost to the end
-
user;


It could have a significant impact on the bandwidth;


It could be associated to spam ope
rations.



AFSCM
Android

development guidelines
v1.1

p
29
/
40


Copyright © AFSCM
2012

3

S
YNTHESIS
OF R
ULES


Section

Rule

ID and

description

Mandatory

Recommended

Information

Specification

Rule
1
:
System properties accessed within method
System.getProperty

must
be hard
-
coded

X



Rule
2
:
The list of all system properties accessed must be provided

X



Rule
3
:
The

list of all external APIs imported by the application must be provided

(including list of pro
prietary APIs and device
-
specific)

X



Rule
4
:
The list of all external APIs packaged with the application’s binary file must be
p牯v楤敤
.

X



P敲eon慬⁤慴a

Rule
5
:
The list of personal data field accessed (db used, content provider used …)
mu獴sb攠p牯v楤敤

X



Rule
6
:
The type (or category) of fields accessed (db used, content provider used …)
mu獴

b攠p牯v楤敤

X



Rule
7
:
The list of files and folders accessed (db used, content provider used …) must
b攠p牯v楤敤

X



Rule
8
:
The type of files manipulated by the application must be provided

X



Rule
9
:
A description of usage of read/write accesses on existing personal data
elements must be provided

X



Rule
10
:
A description of creation/deletion of personal data elements must be
provided

X



Rule
11
:
A descrip
tion of copying, storing and transferring personal data elements
and their destination location must be provided

X



Coding rules

Rule
12
:

Finalizers

should not be

used.


X


Rule
13
:
Imports must be fully imported
.
The
ordering of import statements is:

1. Android imports

2. Imports from third parties (com, junit, net, org)

3. java

and javax

X



Rule
14
:
Usage of access qualifier is encouraged


X


Rule
15
:
Usage of constant and static attributes is encouraged


X


Rule
16
:
Exceptions have to be properly caught and handled

X



Rule
17
:
Exceptions

must not

be

caught and ignored without explanation.

X



Rule
18
:
The
generic
jav
a
.lang.
Exception

should not be the first exception
caught
.


X


Rule
19
:
Clear f
unction separation

is encouraged


X


Rule
20
:
Avoid long class and methods, respect the object oriented programming
philosophy


X


Rule
21
:
Recursion is
prohibited

X



Rule
22
:
All switch statements must include a default rule

X



Rule
23
:
Writing in system output streams shall be prohibited

X



Rule
24
:

The mobile appli
cation developer must take care to the encoding format
which was used in the CARDlet and build String objects with the related format.


x



AFSCM
Android

development guidelines
v1.1

p
30
/
40


Copyright © AFSCM
2012

Section

Rule

ID and

description

Mandatory

Recommended

Information

Publishing

Rule
25
:

Since the package identifier must be unique, the Service Provider must
publish as many variants of applications as there are MNO supported.

X



Rule
26
:

Thus, caution is advised as to the application name that
should include the
MNO n
ame in order to guide the end user the correct application.


X


Rule
27
:

When publishing an update to its application, the SP shou
ld increment the
android:versionCode

property
.


X


NFC

Rule
28
:
Use of Android Gingerbread 2.3, API Level 9 is obsolete and is discouraged


X


Rule

29
:
In order to access

a device's NFC hardware and properly handle NFC intents,
the

following

items
must

be declared
in the
AndroidManifest.xml

file:

X



Rule
30
:
Developer should develop t
he Activity to only handle the NFC tags that the
Activity cares about to prevent the Activity Chooser from appearing.


X


Rule
31
:
The de
veloper must specify
<data>

elements in the
AndroidManifest.xml

along with this intent to correctly handle NFC tags that
start this intent.

X



Rule
32
:
I
f
an
Activity declares the
android.nfc.action.TECH_DISCOVERED

intent in your
AndroidManifest.xml

file, the developer must create an XML
reso
urce file that specifies the technologies that the Activity supports within a tech
-
list set. The Activity is considered a match if a tech
-
list set is a subset of the
technologies that are supported by the tag, which the developer can obtain by
calling
getT
echList()
.

An example is available at the paragraph “Specifying tag
technologies to handle” in the Appendixes
.


X


Rule
33
:
When using the foreground dispatch system, the developer
must

define the
MIME that will be handled. Only the ones needed have to be specified. An example is
available at the paragraph “Using the foreground dispatch system” in the
Appendixes.

X



Controller management

Rule
34
:
[NFC Push
-

Card Emulation] If dynamic registration is performed,
the
registration
string

has to be hard
-
coded. Else it has to be in the manifest.

X



Rule
35
:
The use of the method
basicChannel

is prohibited

X



Rule

36
:
[Open Mobile API]
The c
onnection
string
of the
openLogicalChannel

function
has to be hard
-
coded

X



Rule
37
:
[Open Mobile API] The application only accesses its own cardlets

X



Peer to peer

Ru
le
38
:
The activity that is beaming the data must be in the foreground. Both
devices must have their screens unlocked.

X



Rule
39
:
must encapsulate the data that
he/she

is

beaming in an NdefMessage
object.

X



Rule
40
:
The NFC device that is receiving the beamed data must support the
com.android.npp NDEF push protocol or NFC Forum's SNEP (Simple NDEF Exchange
Protocol). The com.android.npp protocol is required for devices on API level 9
(Android
2.3) to API level 13 (Android 3.2). com.android.npp and SNEP are both
required on API level 14 (Android 4.0) and later.

X



App
laucnch

Rule
41
:
When

using Card Event mechanism

in order to
properly handle NFC events,
the following items have to be declared in the
AndroidManifest.xml

file:

X




AFSCM
Android

development guidelines
v1.1

p
31
/
40


Copyright © AFSCM
2012

Section

Rule

ID and

description

Mandatory

Recommended

Information

Rule
42
:
When using
this

mechanism

in order to
properly handle NFC
external RTD

tags
, the following i
tems have to be declared in the
AndroidManifest.xml

file:

X



UPI and SP
App

Interconnection

Rule
43
:

The
following metadata
must

be declared in the
Androi
dManifest.xml

file

to ensure
UPI
interconnection
:

X



Rule
44
:
UPI interconnection metadata

must be contained in the application that
serves as the main entry into the app (
android.
intent.action.MAIN
).

X



Rule
45
:
NFC
-
App
-
Name

and
NFC
-
app
-
Vendor

must

be constant: no dymanic
value such as “
@string/app_name
”.

X



Connectivity

Rule
46
:
The

application must only use URLs in which the protocol and destination
host are determined.

X



Rule
47
:

URLs must not be dynamically built (the application must use fixed host
strings)
.

X



Rule
48
: The applica
tion must only use HTTP and HTTPS network connections.

X



Rule
49
:
The application should not open connections to numerical IP addresses.


X


Rule
50
:
The application should not open connections to local host.


X


Rule
51
:
File downloading is forbidden, except auto
-
update use case


X


Rule
52
:
The application should only use constant or determined phone numbers


X


Security req
uirements

Ru
le
53
:
Regarding the mandatory
Android

and
Open Mobile

API
s
, the following
permissions
should

be requested by SP
applications
:



X

Rule
54
:
Because some handset already on the market can implement either seek
-
for
-
android 2.2.1 or 2.2.2 and to ensure a retro compatibility, it is recommended to
add both
android.permission.SMARTCARD

and

org.simalliance.openmobileapi.SMARTCARD

permissions
)


X


Rule
55
:

In order to make the application installable and visible on the market only
to handsets supporting the Open Mobile APIs, the Android Manif
est.xml must
contain the following line:

<uses
-
library
android:name="org.simalliance.openmobileapi"
android:required="true" />

X



Rule
56
:
The application
must
not access any
non
-
public
resources

of other
applications
.

X



Rule
57
:
The application
must

not access
the user’s MSISDN
.

X



Rule
58
:
Expl
icit usage of garbage collection is strongly discouraged.


X


Rule
59
:
The application must not alter personal information

X



Rule
60
:
The application verifies the consistency of its
database


X


Rule
61
:
The application should p
erform
verification to preserve system integrity


X


Rule
62
:
The application should

preserve RFID tags integrity


X


Rule
63
:
The application verifies the consistency of its files


X


Rule
64
:
The application does not define default passwords for accessing its services.


X


Rule
65
:
Application’s secrets are not hard coded plaintext in the code.


X


Rule
66
:
Secrets are not stored as plaintext.

X



Rule
67
:
Avoid decrypting secrets for comparison.

X



Rule
68
:
The application does not send Operator and third party data.

X



Rule
69
:
The a
pplication does not send device localization data

(without end user
approval)
.

X




AFSCM
Android

development guidelines
v1.1

p
32
/
40


Copyright © AFSCM
2012

Section

Rule

ID and

description

Mandatory

Recommended

Information

Rule
70
:

The application does not send identification data

(without end user
approval)
.

X



Rule
71
:
The application does not send device configuration data

(without end user
approval)
.

X



Rule
72
:
The application

ensures personal data cannot be exploited remotely

(without end user approval)
.

X



Rule
73
:
The application implements mutual authentication mechanisms.


X


Rule
74
:
The design of the service prevents replay attacks.


X


Rule
75
:
The application uses encrypted communicati
ons.


X


Rule
76
:
The application must handle the cases when the cardlet is not present.

X



Environment
protection

Rule
77
:
The application shall not send any executable program to remote entities.

X



Rule
78
:
Executable code in SMS/MMS bina
ry messages is forbidden.

X



Rule
79
:
The applicatio
n shall not intensively use network resources.

X




4

A
PPENDI
C
ES

4.1.1

NFC Demo sample

http://developer.android.com/resources/samples/NFCDemo/index.html

This demo application shows how to read a NDEF Tags using Android 2.3 SDK APIs.

For an appl
ication that uses the NFC API, remember that the feature is supported only on Android 2.3
(API level 9) and higher versions of the platform. Also, among devices running Android 2.3 (API level
9) or higher, not all devices will offer NFC support. To ensure
that your application can only be
installed on devices that are capable of supporting NFC, remember to add the following to the
application's manifest before publishing to Android Market

/ Google Play
:

<uses
-
sdk android:minSdkVersion="9"/>
, which indicates

to Android Market

/ Google
Play

and the platform that the application requires Android 2.3 or higher.


Minimum SDK version 9 is deprecated, minimum SDK version 10 (Android 2.3.4) must be used.

Following
is
the AndroidManifest.xml of the NFC Demo:

<?xml ve
rsion="1.0" encoding="utf
-
8"?>

<!
--

Copyright (C) 2010 The Android Open Source Project



Licensed under the Apache License, Version 2.0 (the "License");


you may not use this file except in compliance with the License.


You may obtain a copy of

the License at



http://www.apache.org/licenses/LICENSE
-
2.0



Unless required by applicable law or agreed to in writing, software


distributed under the License is distributed on an "AS IS" BASIS,


WITHOUT WARRANTIES OR CONDITIONS OF
ANY KIND, either express or implied.


See the License for the specific language governing permissions and


limitations under the License.

--
>


AFSCM
Android

development guidelines
v1.1

p
33
/
40


Copyright © AFSCM
2012


<!
--

Declare the contents of this Android application. The namespace


attribute brings in the Androi
d platform namespace, and the package


supplies a unique name for the application. When writing your


own application, the package name must be changed from "com.example.*"


to come from a domain that you own or have control over.
--
>

<manifes
t xmlns:android="http://schemas.android.com/apk/res/android"


package="com.example.android.nfc"

>


<uses
-
permission android:name="android.permission.NFC" />


<uses
-
permission android:name="android.permission.CALL_PHONE" />


<application



android:icon="@drawable/icon"


android:label="@string/app_name"


>


<activity android:name=".simulator.FakeTagsActivity"


android:theme="@android:style/Theme.NoTitleBar">


<intent
-
filter>


<action android:name="androi
d.intent.action.MAIN" />


<category android:name="android.intent.category.LAUNCHER" />


</intent
-
filter>


</activity>


<activity android:name="TagViewer"


android:theme="@android:style/Theme.NoTitleBar"


>



<intent
-
filter>


<action android:name="android.nfc.action.TAG_DISCOVERED"/>


<category android:name="android.intent.category.DEFAULT"/>


</intent
-
filter>


</activity>


</application>


<uses
-
sdk
android:minSdkVersion="
10
" />


<uses
-
feature android:name="android.hardware.nfc" android:required="
true
" />

</manifest>


4.1.2

Specifying tag technologies to handle

For example, if the tag that is scanned supports MifareClassic, NdefFormatable, and NfcA,
the

tech
-
list set must specify all three, two, or one of the technologies (and nothing else) in order for
the

Activity to be matched.


The following sample defines all of the technologies.
The developer

can remove the ones that you do
not need. Save this file
(you can name it anything you wish) in the <project
-
root>/res/xml folder.


<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>android.nfc.tech.Ndef</tech>


<tech>android.nfc.tech.NdefFormatable</tech>


<tech>android.nfc.tech.Mifar
eClassic</tech>


<tech>android.nfc.tech.MifareUltralight</tech>


</tech
-
list>

</resources>



AFSCM
Android

development guidelines
v1.1

p
34
/
40


Copyright © AFSCM
2012

The developer

can also specify multiple tech
-
list sets. Each of the tech
-
list sets is considered
independently, and
the

Activity is considered a match if
any single tech
-
list set is a subset of the
technologies that are returned by getTechList(). This provides AND and OR semantics for matching
technologies. The following example matches tags that can support the NfcA and Ndef technologies
or can support the

NfcB and Ndef technologies:


<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">


<tech
-
list>


<tech>android.nfc.tech.NfcA</tech>


<tech>android.nfc.tech.Ndef</tech>


</tech
-
list>

</resources>


<resources xmlns:xlif
f="urn:oasis:names:tc:xliff:document:1.2">


<tech
-
list>


<tech>android.nfc.tech.NfcB</tech>


<tech>android.nfc.tech.Ndef</tech>


</tech
-
list>

</resources>


In
the

AndroidManifest.xml file,
the developer
specif
ies

the resource fi
le that
he/she

just created in
the <meta
-
data> element inside the <activity> element like in the following example:


<activity>

...

<intent
-
filter>


<action android:name="android.nfc.action.TECH_DISCOVERED"/>

</intent
-
filter>


<meta
-
data android:name="a
ndroid.nfc.action.TECH_DISCOVERED"


android:resource="@xml/nfc_tech_filter" />

...

</activity>

4.1.3

Using the foreground dispatch system

To enable the foreground dispatch system:

1.

Add the following code in the onCreate() method of
the

Activity:

a)

Create a Pendi
ngIntent object so the Android system can populate it with the details of
the tag when it is scanned

PendingIntent pendingIntent = PendingIntent.getActivity(


this, 0, new Intent(this,
getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0
);


b)

Declare intent filters to handle the intents that
the developer

want
s

to intercept. The
foreground dispatch system checks the specified intent filters with the intent that is
received when the device scans a tag. If they match, then
the

application han
dles the
intent. If it does not match, the foreground dispatch system falls back to the intent
dispatch system. Specifying a null array of intent filters and for the technology filters,
the developer

receive
s

a TAG_DISCOVERED intent for all tags discovered
. Note that the
snippet below handles all MIME types.
O
nly
the needed ones have to be handled
.


IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);

try {


ndef.addDataType("*/*");

}catch (MalformedMimeTypeException
mmtex
) {


L
og.e("ForegroundDispatch", mmtex.getMessage(), mmtex);

}

intentFiltersArray = new IntentFilter[] {ndef};


AFSCM
Android

development guidelines
v1.1

p
35
/
40


Copyright © AFSCM
2012


c)

Set up an array of tag technologies that
the

application wants to handle. Call the
Object.class.getName() method to obtain the class of the technolog
y that
the developer

want to support.

techListsArray = new String[][] { new String[] {
Ndef
.class.getName() } };


2.


Override the following Activity lifecycle callbacks and add logic to enable and disable the
foreground dispatch when the Activity loses (onPa
use()) and regains (onResume()) focus.
enableForegroundDispatch(Activity, PendingIntent, IntentFilter[], String[][]) must be called from
the main thread and only when the activity is in the foreground (calling in onResume()
guarantees this).
The developer

also need
s

to implement the onNewIntent callback to process
the data from the scanned NFC tag.

public void onPause() {


super.onPause();


mAdapter.disableForegroundDispatch(this);

}


public void onResume() {


super.onResume();


mAdapter.enableF
oregroundDispatch(this, pendingIntent, intentFiltersArray,
techListsArray);

}


public void onNewIntent(Intent intent) {


Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);


//do something with tagFromIntent

}



AFSCM
Android

development guidelines
v1.1

p
36
/
40


Copyright © AFSCM
2012

4.1.4

Using Foreground Disp
atch with NDEF

4.1.4.1

AndroidManifest.xml

<?xml version="1.0" encoding="utf
-
8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"


package="com.example.afscm.apis"


android:versionCode="1"


android:versionName="1.0" >



<uses
-
permi
ssion android:name="android.permission.NFC" />


<uses
-
feature android:name="android.hardware.nfc" android:required="true" />




<uses
-
sdk android:minSdkVersion="10" />



<application


android:icon="@drawable/ic_launcher"


android:
label="@string/app_name" >


<activity


android:name=".TestNFCActivity"


android:label="@string/app_name" >


<intent
-
filter>


<action android:name="android.intent.action.MAIN" />


<catego
ry android:name="android.intent.category.LAUNCHER" />


</intent
-
filter>


</activity>




<activity


android:name=".ForegroundNdefPush"


android:label="@string/activity_sample_code"


android:la
unchMode="singleTask" >


<intent
-
filter>


<action android:name="android.nfc.action.NDEF_DISCOVERED" />


<category android:name="android.intent.category.DEFAULT" />


<data


android:h
ost="ext"


android:pathPrefix="/
example.com:externalType
"


android:scheme="vnd.android.nfc" />


</intent
-
filter>


</activity>




</application>


</manifest>


AFSCM
Android

development guidelines
v1.1

p
37
/
40


Copyright © AFSCM
2012

4.1.4.2

ForegroundNdefPush
.java

package
com.example.afscm.apis.nfc;


import com.example.afscm.apis.R;

import android.app.Activity;

import android.nfc.NdefMessage;

import android.nfc.NdefRecord;

import android.nfc.NfcAdapter;

import android.os.Bundle;

import android.widget.TextView;


import java.
nio.charset.Charset;

import java.util.Locale;


/**


* An example of how to use the NFC foreground NDEF push APIs.


*/

public class ForegroundNdefPush extends Activity {


private NfcAdapter mAdapter;


private TextView mText;


private NdefMessage mM
essage;




public static NdefRecord newTextRecord(String text, 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 = text.getBytes(utfEncoding);


int utfBit = encodeInUtf8 ? 0 : (1 << 7);


char status = (char) (utfBit + langBytes.length);


byte[] data = new byte[1 + langBytes.length + t
extBytes.length];


data[0] = (byte) status;


System.arraycopy(langBytes, 0, data, 1, langBytes.length);


System.arraycopy(textBytes, 0, data, 1 + langBytes.length, textBytes.length);


return new NdefRecord(NdefRecord.TNF_WELL_K
NOWN, NdefRecord.RTD_URI, new byte[0],
data);


}



@Override


public void onCreate(Bundle savedState) {


super.onCreate(savedState);


mAdapter = NfcAdapter.getDefaultAdapter(this);


setContentView(R.layout.foreground_dispatch)
;


mText = (TextView) findViewById(R.id.text);


if (mAdapter != null) {


mText.setText("Tap another Android phone with NFC to push 'NDEF Push Sample'");


} else {


mText.setText("This phone is not NFC enabled.");


}


// Create an NDEF message with some sample text


mMessage = new NdefMessage(


new NdefRecord[] { newTextRecord("NDEF Push Sample", Locale.ENGLISH, true)});


}



@Override


public void onResume() {



super.onResume();


if (mAdapter != null) mAdapter.enableForegroundNdefPush(this, mMessage);


}



@Override


public void onPause() {


super.onPause();


if (mAdapter != null) mAdapter.disableForegroundNdefPush(this);


}

}


AFSCM
Android

development guidelines
v1.1

p
38
/
40


Copyright © AFSCM
2012

4.1.5

Using Smart Card
-
based features

4.1.5.1

Usage pattern

The usage pattern of the API is as follows:

1.

The application gets access to the Secure Element service(s): It creates a SEService class, passing
an object implementing the SEService.Callback interface, whose

serviceConnected method is
called asynchronously when the connection is established. This doesn’t represent a connection
with the SE itself, but with the subsystem implementing the Secure

Element access functionality.

2.

The application enumerates the availa
ble readers. Readers are the slots where SEs are connected
(in a removable or
non
-
removable

manner).

Once the user or an application
-
specific algorithm
has selected a Reader, then the application opens

a Session on this reader.

3.

With this session, the appli
cation can retrieve the ATR of the SE, and if it matches with one of the

known ATRs, it can start opening channels with applications in the SE.

4.

To open a channel, the application will use the AID of the SE application or use the default SE

application on t
he newly opened channel.

5.

Then the terminal application can start transmitting APDUs to the SE application
.

6.

Once done, the application can close any existing channel
s or even sessions, and it
s connection

to the SEService.

4.1.5.2

Sample code

-

Initialize the
Secure E
lement

Access

o

Create a handle to the SmartCard API. At the end of the
onCreate()

method, add

try {


seService = new SEService (this, this);

} catch (SecurityException seex) {


Log.e("DemoCouponingAndroid", seex.getMessage(), seex);

}

o

create a
SEServi
ce

and a
Callback
objects within the
MainActivity

class

SEService

seService
;

o

and implement a
CallBack
class

/**

* Callback interface if informs that this SEService is connected to the

* backend syst
em and
its

resources.

*/

public class SEServiceCallback im
plements CallBack {



/**


* This method will be called if this SEService is connected


*/


public void serviceConnected(SEService service) {


performsOperations(service);


}

}



Note: the constructor of
SEService

will automatically bind
to the SEService interface in the
background. Since service binding is asynchronous in Android, the proper way to initialize the
library is to wait for a notification event as discussed later.


In order to be allowed to use the SmartCard API, an application

must implement the
SMARTCARD

permission
s
.
These permissions

notif
y

a user when installing an application that
requests access to a Secure Element. Define the permission
s

in the
AndroidManifest.xml

file :



<uses
-
permission android:name="android.permission.
SMARTCARD"/>


<uses
-
permission android:name="org.simalliance.openmobileapi.SMARTCARD"/>



AFSCM
Android

development guidelines
v1.1

p
39
/
40


Copyright © AFSCM
2012

-

Accessing the Smart Card

void performsOperations(SEService service) throws Exception{


Reader[] readers;


int readerIndex = 0;


Session seSession =

null;


Channel seChannel;


this.seService = service;


try {


readers = seService.getReaders();


for (int i = 0; i < readers.length; i++) {



Log.d("SEServiceCallback", "readers["+i+"]:" + readers[i]
.getName());


if ((readers[i].getName().equals("UICC") ||
readers[i].getName().startsWith("SIM"))


&& readers[i].isSecureElementPresent()) {


readerIndex = i;


}


}



seSession = readers[readerIndex].openSession();


if(seSession == null) return;


seChannel = seSession.openLogicalChannel(new byte[] {0x01, 0x02, 0x03, 0x04,
0x05, 0x06, 0x07, 0x08, 0x09, 0x00, 0x00});


if(seChannel ==
null) return;


//init coupon list


for (byte i = 0; i < 5; i++){


this.respApdu = seChannel.transmit(new byte[] { (byte)0x80, 0x30, 0x00,
0x00, 0x01, i, 0x5F });


if(this.respApdu != null){



Toast.makeText(this, "" + printHexStringArray(this.respApdu),
Toast.LENGTH_LONG);


Log.d("DemoCouponingAndroid", printHexStringArray(this.respApdu));


}else{


Toast.makeText(this, "does not work",
Toast.LENGTH_LONG);


Log.d("DemoCouponingAndroid", "does not work");


}


}


seChannel.close();


readers[readerIndex].closeSessions();



} catch (IOException ioex) {



ioex.printStackTrace();


}

}

In this code, a logical channel to the applet identified by its AID
01 02 03 04 05 06 07 08 09 00
00

is created. The applet specific APDU command
80 30 00 00 01 00 5F

is sent to retrieve the
applet response.

The last two bytes of the response (=status word or SW1SW2), typically 90 00 on successful
execution of the command are truncated and the result is displayed on the screen.



AFSCM
Android

development guidelines
v1.1

p
40
/
40


Copyright © AFSCM
2012

-

Closing the SmartCard Access

o

To clean up the service binding, call the shutdown m
ethod when the application is
closing or is not using smart card services anymore (for example, in onDestroy())

@Override

protected

void

onDestroy
()

{


if (seService != null && seService.isConnected()) {



seService.shutdown();


}


super.onDestroy();

}

-

Exa
mple of an AndroidManfest.xml of an application which uses the SIMalliance standardized
interface OpenMobileAPI
:

<?xml version="1.0" encoding="utf
-
8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"


package="com.orangelabs.democou
poning"


android:versionCode="1"


android:versionName="1.0" >



<uses
-
sdk android:minSdkVersion="10" />


<uses
-
permission android:name="org.simalliance.openmobileapi.SMARTCARD"/>




<application


android:icon="@drawable/icon"


android:label="@string/app_name" >


<uses
-
library

android:name="org.simalliance.openmobileapi" android:required="true" />
a


<activity


android:name=".DemoCouponingAndroidActivity"


android:label="@string/app_name" >



<intent
-
filter>


<action android:name="android.intent.action.MAIN" />


<category android:name="android.intent.category.LAUNCHER" />


</intent
-
filter>


</activity>


</application>

</manifest>



-

Othe
rs full examples can be found at:

http://code.google.com/p/seek
-
for
-
android/source/browse/trunk/samples/OpenMobileApiSample/

(seek
-
for
-
android 2.2.
1)

http://code.google.com/p/seek
-
for
-
android/wiki/UsingSmartCardAPI

(seek
-
for
-
android 2.2.2

and later
)




END OF DOCUMENT





a

The uses
-
library tag must

be in the <
application
>
tag
and only in this tag