NFC Android applications development guidelines

imaginaryfleetΚινητά – Ασύρματες Τεχνολογίες

19 Ιουλ 2012 (πριν από 4 χρόνια και 10 μήνες)

1.848 εμφανίσεις






AFSCM

Android
d
evelopment
g
uidelines


p
1
/
36


Copyright © AFSCM 20
11










NFC Android applications development guidelines









RELEASE

1.0
.1

Date


14/12
/20
11

Reference

111214
-

AFSCM TECH
-

LIVBL
-

Android Development Guidelines
-

v1.0.1.doc




AFSCM
Android

development guidelines
v1.0
.1

p
2
/
36


Copyright © AFSCM
2011



Name

Company

Authors

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
Hallay

Orange


Document management


Version

Date

Chapters

Modification

0.1

02/22/2011

All

Document creation

0.1
8

14
/09/2011

All

First DRAFT version

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

Up
dated
Smart Card API
permissions (
seek
-
for
-
android 2.2.2
)

Metadata: added
NFC
-
Service
-
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” se
捴con⁡湤⁲畬es

1⸰⸱

14I12I2011

2⸸⸲

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

N䙃
-
卥Sv楣i
-


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




AFSCM
Android

development guidelines
v1.0
.1

p
3
/
36


Copyright © AFSCM
2011


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

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

13

2.3.1

Activity

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

13

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

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

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 Sy
stem 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.8

User primary interface and Service Provider application interconnection

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

21

2.8.1

Goal

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

21

2.8.2

Metadata definition

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

21

2.8.3

Code samples

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

22

2.9

Connectivity

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

22

2.9.1

General Requirements

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

22

2.9.2

Network

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

23


AFSCM
Android

development guidelines
v1.0
.1

p
4
/
36


Copyright © AFSCM
2011

2.9.3

Server Requests

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

23

2.10

Security Requirements

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

23

2.10.1

Common security features

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

23

2.10.2

Open Mobi
le API security features

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

24

2.10.3

Local protection of assets

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

24

2.10.4

Prohibited/Restricted resources

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

24

2.10.5

Memory usage

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

24

2.10.6

Alteration of assets

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

24

2.10.7

Confidential assets

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

25

2.10.8

Protection of assets among network communications

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

25

2.10.8.1

Prohibited transmissions

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

26

2.10.8.2

Personal data: restricted situations

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

26

2.10.8.3

Secured transmissions

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

26

2.11

Protecti
on of the Environment

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

27

3

S
YNTHESIS OF RULES

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

28

4

A
PPENDICES

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

31

4.1.1

NFC Demo sample

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

31

4.1.2

Specifying tag technologies to handle

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

32

4.1.3

Using the foreground dispatch system

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

33

4.1.4

Using Smart Card
-
based features

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

34

4.1.4.1

Usage pattern

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

34

4.1.4.2

Sample code

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

34





TABLE OF FIGURES

________________________________
______________________________


Figure 1


Activity lifecycle

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

13

Figure 2


Service lifecycle

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

14




AFSCM
Android

development guidelines
v1.0
.1

p
5
/
36


Copyright © AFSCM
2011

1

I
NTRODUCTION

1.1

Context

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

The Servi
ce Providers
Credit Mutuel, Société Générale and Véolia have already joined the AFSCM
as associate members
.

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

In particular, AFSCM endeavors:

-

To support servi
ce providers such as banks or transit authorities in the definition and
deployment of contactless 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 distinguish those contactless services
that are available to mobile phone users.

AFSCM constituency will include all companies involved in the development of a sustain
able
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 services.

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,

-

State
-
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 Op
erator

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 specificatio
ns.

The licensee is authorized to copy, present or communicate the AFSCM specifications on any 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.0
.1

p
6
/
36


Copyright © AFSCM
2011

The specifications i
nclude detailed functional specifications, technical specifications, NFC handset
and NFC UICC 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 i
s contained in Annex 1.

THE SPECIFICATIONS ARE SUPPLIED "AS IS" AND NEITHER THE AFSCM NOR ITS MEMBERS ARE
COMMITTED TO ANY WARRANTY, EXPLICIT OR IMPLICIT, REGARDING THE SPECIFICATIONS, IN
PARTICULAR NO WARRANTY IS GIVEN OF QUALITY, SUITABILITY TO ANY USE W
HATSOEVER,
ABSENCE OF TITLE OR RIGHTS TO THE CONTENT OF THE SPECIFICATIONS, INSURANCE THAT THE
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 MEM
BERS
SHALL BE HELD LIABLE FOR ANY DAMAGE INCURRED IN CONNECTION TO THE USE,
REPRESENTATION OR 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 spe
cifications without the prior written agreement of the AFSCM.

No rights other than the rights 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
inventions, 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 Fren
ch law and shall be governed by and interpreted according
to French laws. The exclusive place 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 a
cceptance of these terms and
conditions.

(*) : AFSCM founding members are : Bouygues Telecom, 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 p
roperly
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
applic
ation

appropriate for the
context of NFC services.


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

development in these documents.



The safety of a Android appl
ication 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 embed
ded
on mobile handset they require particular care in the usage of the operator and device resources.


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 applications are difficult to update. Thus, developers

AFSCM
Android

development guidelines
v1.0
.1

p
7
/
36


Copyright © AFSCM
2011

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

-

Coding ru
les

Most principles of good standard Java practices apply to Android applications. Some of them
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.

-

Portability considerations

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

-

NFC Controller management

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

-

UICC Management

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

-

Local database management

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

-

Application launch

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

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

-

User Primary Interface and Service Provider interconnection

This paragraph presen
ts the rules in order to register properly the Service Provider application
with regard to the 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 servers.

-

Security

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

-

Protection of the environment

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


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


Good pract
ice

/
R
ecommended


Forbidden


Warning

/ Mandatory


AFSCM
Android

development guidelines
v1.0
.1

p
8
/
36


Copyright © AFSCM
2011

1.4

References

AFSCM:

The following documents are available for the Service Providers:

[R1] Interface Specification
between

Telecom Operators and NFC Service Providers

[R2] NFC Applications Validation Proces
s

[R3] Cardlet Development Guide

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

The AFSCM also specifies high level requirements for both UICC and mobile handset in separate
documents. These documents are only provi
ded 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
-
style.html

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

http://developer.android.com/guide/publishing/preparing.html

http://developer.android.com/guide/topics/
nfc/index.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 Spe
cification Request

MIDP

Mobile Information Device Profile

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

UICC

Un
iversal Integrated Circuit Card (aka SIM)

UPI

User Primary Interface


AFSCM
Android

development guidelines
v1.0
.1

p
9
/
36


Copyright © AFSCM
2011

URL

Uniform Resource Locator

URI

Uniform Resource Identifier

Cardlet


Java Card

application hosted in UICC



AFSCM
Android

development guidelines
v1.0
.1

p
10
/
36


Copyright © AFSCM
2011

2

M
ANAGEMENT RULES

2.1

Development process

The entire development process needs

to be adapted to the specific aspects of Android. In
particular, 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 int
egrating this
issue into the development process (e.g. usage 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 applicat
ion, the specification should particularly take car of:


Define 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 transferre
d data.

This specification should particularly consider the 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 a
nd could manipulate end
-
user
personal data. It is the responsibility 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 se
nsitive 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

Dependencies 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 propertie
s and APIs features accessed by the application must be
documented and transmitted to the Validation Entity for certification purposes [R2]
:


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

(
see
System.getPropertie
s

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 proprietary 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 e
xternal classes provided by Apache, XML parsing or
cryptographic libraries.



AFSCM
Android

development guidelines
v1.0
.1

p
11
/
36


Copyright © AFSCM
2011

2.1.3

Usage of personal data

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

The
following 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 o
f 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 o
n existing personal data elements must
be provided


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


Rule
11
:
A description of copying, storing and transferring personal dat
a elements and their
destination location must be provided


More details can be found at
http://android
-
developers.blogspot.com/2010/08/best
-
practices
-
f
or
-
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 inc
luding 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 applications on each targeted device.

2.2

Coding rules

Since And
roid 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 consistent 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


Ru
le
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 for applications, there are several reasons for which i
t is interesting
to deal with classes, methods or fields attributes.



AFSCM
Android

development guidelines
v1.0
.1

p
12
/
36


Copyright © AFSCM
2011

Encapsulation

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

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 handl
ed


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 sepa
ration

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
maintain.


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 appropriate, so no hard limit is placed on
method lengt
h. 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 defaul
t 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 chain (from server to
handset). Thus she/he has to be con
sistent 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 application 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 data returned by the CARDlet are “Latin
-
1” encoded and co
ntains 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.



AFSCM
Android

development guidelines
v1.0
.1

p
13
/
36


Copyright © AFSCM
2011

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 as the "main" activity, which is presented to the user
when 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 can perform long
-
running operations in the background
an
d 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
component can bind to a service to interact with it and e
ven 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.0
.1

p
14
/
36


Copyright © AFSCM
2011

2.3.4

Service lifecycle


Figure
2



Ser
vice 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 distribution and installation of bundled
components onto t
he Android mobile device platform.

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


META
-
INF


res

and files:


AndroidManifest.xml


classes.dex


resources.arsc

2.5

Publishing an application

2.5.1

Preparing to Publish

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

Before considering an application ready for re
lease:


Test the application extensively on
several

actual device
s


AFSCM
Android

development guidelines
v1.0
.1

p
15
/
36


Copyright © AFSCM
2011


Consider adding an End User License Agreement 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 suitable cryptographic key


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

Compile the application
.

After compiling the applic
ation
:


Sign the application


Test the signed application

2.5.2

Publishing on Android Market


To publish an application on Android Market, 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 published, 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 M
arket, it has to meet the requirements listed below, which
are enforced by the Market server when the application is uploaded.

Requirements enforced by the Android Market server:


The application must be signed with a cryptographic private key whose validit
y 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 applicatio
n internally and
handling updates, and it displays the
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 prov
ider shall take care

that the application
s

will be shown

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 applic
ation can only be signed once. To allow access to the UICC application, this signature is
the signature of the MNO.



Rule
25
:

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


Rule
26
:

Thus, caution is advised as to the application name that
should include the MNO
name 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.0
.1

p
16
/
36


Copyright © AFSCM
2011

2.5.4

Application update



Rule
27
:

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

property
.


2.6

NFC
Fea
t
ures

2.6.1

NFC management

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


Card/Tag writing/reading


Card emulation


Peer
-
to
-
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 typically refers to the mechanism or ability to receive and act on information
asynchronously, as information becom
es 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 functionality, allowing
applications to read NDEF message in NFC tags. A "tag" may actually be another device that
appear
s 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

fo
llowing

items
must

be declared
in the
AndroidManifest.xml

file:

1.

The NFC
<uses
-
permission>

element to access the NFC hardware:

<uses
-
permission

android: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_MESSAGES

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

<uses
-
sdk

android:minSdkVersion="10"/>

3.

The uses
-
feature element so that the application can show up in the Android Market for
devices that have NFC hardware:

<uses
-
feature

android:name="android.hardware.nfc"

android:required="tr
ue"

/>


AFSCM
Android

development guidelines
v1.0
.1

p
17
/
36


Copyright © AFSCM
2011

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:mimeTy
pe="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 specific 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 application to use. Because devices scan
NFC tags at a very short range, it is likely that making users manually select an Activity fo
rces them
to move the device away from the tag and break the connection.


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


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


the Intent dispatch system 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
t
o the user as a last resort.

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


android.nfc.action.NDEF_DISCOVERED


android.nfc.action.TECH_DISCOVERED


android.nfc.action.TAG_DISCOVERED

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


android.nfc.action.NDEF_DISCOVERED
: 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.0
.1

p
18
/
36


Copyright © AFSCM
2011


Rule
31
:
The developer must specify
<data>

elements in the
AndroidManifest.xml

along with this intent to correctly handle NFC tags that sta
rt this intent.

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

<intent
-
filter>


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


<data android:mime
Type="text/plain" />

</intent
-
filter>

If the
NDEF_DISCOVERED

intent is started, the
TECH_DISCOVERED

and
TAG_DISCOVERED

intents are not started.

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


androi
d.nfc.action.TECH_DISCOVERED
: If the
NDEF_DISCOVERED

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

intent requires that the developer specifies the technologies that he/s
he
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
Act
ivity declares the
android.nfc.action.TECH_DISCOVERED

intent in
your
AndroidManifest.xml

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

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


The
foregrou
nd

dispatch system

The foreground dispatch system

allows an Activity application to override the intent dispatch
system and have priority 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 sent 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 and claim priority over
other Activities that handle the same intent. The system is easy to use and involves constructing a
f
ew 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 nee
ded have to be specified. An example is available at the
paragraph “Using the foreground dispatch system” in the Appendixes.


More details 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/index.html#ndef
,


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


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


AFSCM
Android

development guidelines
v1.0
.1

p
19
/
36


Copyright © AFSCM
2011

2.6.5

Card Emulation

For more information 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 specification 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 found at the following URL:
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/doc/index.html
.

2.6.5.2

Security
C
onsiderations

At install
ation

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


Access to the lower layer components such as the secure element specific terminal
implementation 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 replaces APKs or native system services with modified versions that
contain tracers or hooks for other applications. This means that t
he security concept of the
Smartcard API can be broken on rooted phones but this is not an issue of the API design but a
general issue on Linux based systems where root can do everything.

2.6.5.3

SmartCard API System Security

The security considerations for the Sm
artCard 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 clien
t
applications cannot overcome the SmartCard API interface by using the lower level components
directly.

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

All low lev
el components and methods check for the caller UID and
-

if not smartcard
-

throw an
exception.

2.6.5.4

Access Control

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

on the technologie
s 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. Accord
ing
permissions are stored in the SE or in the signed application itself.


The other one is based on the Seek
-
For
-
Android mechanism: “
The access control scheme of
the SmartCard API is a protection mechanism that ensures that only allowed (or certified)
Andr
oid 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.0
.1

p
20
/
36


Copyright © AFSCM
2011


The app
lication 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

S
imple peer
-
to
-
peer data exchange is supported by the foreground push feature, which is enabled
with the
enableForegroundNdefPush(A
ctivity, NdefMessage)

method.

To use this feature:


Rule
38
:
The Activity that is pushing the data must be in the foreground


Rule
39
:
The developer must encapsulate the data that he/she is sending in an
NdefMess
age

object


Rule
40
:
The NFC device that is receiving the pushed data (the scanned device) must support
the
com.android.npp

NDEF push protocol, which is optional for Android devices.

If the Activity enables the foreground push feature

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
-
t
o
-
Peer are available at:

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

2.7

NFC Application

Launch

2.7.1

Via User Primary Interface

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

UPI will produce a call to
startActivity (Intent intent)

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 C
ard Event (HCI) mechanism

The
card event mechanism

enables applications to set themselves up to be launched 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>

e
lement to use the NFC Event:

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

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

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

3.

The NFC intent filter to tell the And
roid 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.TRANSACTION_DETECTED"></action>

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




<data


android:scheme="nfc"


android:host="secure"


AFSCM
Android

development guidelines
v1.0
.1

p
21
/
36


Copyright © AFSCM
2011


android:port="0"


android:path="/4e464354657374657220312e30"/> <!
--

AID
--
>

</intent
-
filter>

4.

The application has to be launched in single tas
k 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:launchMode="singleTask"

android:screenOrientation="portrait">

Moreover the met
hod
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 appli
cation can show up in the Android Market for
devices that have NFC hardware:

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


2.8

User primary interface and Service Provider
application
interconnection

2.8.1

Goal

As announced in the intr
oduction

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

2.8.2

Metadata definition

The UPI will collect the application’s i
nformation from its
Android Manifest.xml file.



Rule
42
:
The
following metadata
must

be declared in the
AndroidManifest.xml

file

to
ensure
UPI
interconnection
:


android:label
: ASCII. This is the name the UPI will display to users in t
he 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.
About the icon
s

to be used, application must
define three
sizes

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



ldpi: 36*36 pixels;



mdpi: 48*48 px;



hdpi: 72*72 px.



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

for more information.


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


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



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

AFSCM
Android

development guidelines
v1.0
.1

p
22
/
36


Copyright © AFSCM
2011

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
43
:
UPI interconnection metadata

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


Rule
44
:
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
application
. This information can actually be inferred if the URLs comply with simple constraints
such as specifying a determined scheme.


AFSCM
Android

development guidelines
v1.0
.1

p
23
/
36


Copyright © AFSCM
2011


Rule
45
:
The

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


Rule
46
:

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

2.9.2

Network


Rule
47
: 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
48
:
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
49
:
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
50
:
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


Rule
51
:
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

Security
Require
ments

2.10.1

Common security features

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




Rule
52
:
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 needed to launc
h 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.SMARTCARD

(for Seek
-
for
-
Android
2.2.2


new permission
)


Rule
53
:
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

AFSCM
Android

development guidelines
v1.0
.1

p
24
/
36


Copyright © AFSCM
2011

android.permission.SMART
CARD

and

org.simalliance.openmobileapi.SMARTCARD

permissions
)


Rule
54
: In order to make the application installable and visible on the market only to
handsets supporting the Open Mobile APIs, the Android Manifest.xml must contain the

following line:

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

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

Whatever the security level reached by the application,
Se
rvice 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

The SmartCard API uses the Android permission scheme to protect access to secure elements.
Therefor
e it defines permission
s

(
android.permission.SMARTCARD

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

Additional security features exist specifically for the
Open Mob
ile
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 t
o 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 d
uring their manipulation.

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

2.10.4

Prohibited/Restricted resources


Rule
55
:
The application
must
not access any
no
n
-
public
resources

of other applications
.


Rule
56
:
The application
must

not access
the user’s MSISDN
.

2.10.5

Memory usage

Applications are intended 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 tak
e a long time to proceed. In addition, there
is no guarantee the requested collection operation is immediately performed.


Rule
57
:
Explicit usage of garbage collection is strongly discouraged.

2.10.6

Alteration of assets

Applications are no
t 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.

Then, the application must particularly consider the following requireme
nts.


AFSCM
Android

development guidelines
v1.0
.1

p
25
/
36


Copyright © AFSCM
2011


Rule
58
:
The application must not alter personal information

without user consent

For security reason, applications are not supposed 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
59
:
The application verifies the consistency of its
database

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

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


Rule
60
:
The application should p
erform
verification to preserve sy
stem integrity

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

The application must implement safety verifications that restrict destination fol
ders 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
61
:
The application should

preserve RFID tags integri
ty

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 implement safety verifications that restrict records and offsets being
modified.


Rule
62
:
The application verifies the consistency of its files

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

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 passwords) or application
-
own asset (
e.g.
, activation or encryption
keys).


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

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


Rule
64
:
App
lication’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 contai
ns.


Rule
65
:
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 applicati
on must implement encryption features to protect these
secrets.


Rule
66
:
Avoid decrypting secrets for comparison.

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

2.10.8

Protection of assets among network communications

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


AFSCM
Android

development guidelines
v1.0
.1

p
26
/
36


Copyright © AFSCM
2011

2.10.8.1

Prohibited transmissions

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


Rule
67
:
The appl
ication does not send Operator and third party data.

Usage of Operator data should be restricted to local computations.


Rule
68
:
The application does not send device localization data

(without end user approval)
.

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


Rule
69
:

The application does not send identification da
ta

(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
70
:
The application does not send device configurati
on 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 situatio
ns

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

In nominal situations they are not intended to be transmitted to any remote 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 mu
st not be exploitable by any entity except
the local
application
, as stated in the security requirement

below
:


Rule
71
:
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, the
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 m
echanisms, especially to prevent social
-
engineering attacks.


Rule
72
:
The application implements mutual authentication mechanisms.

There 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.
, requesting the local agent
to perform costly operations) or the device (
e.g.
, download of malicious applic
ations).

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


Rule
73
:
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 requests 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
74
:
The application uses encrypted communications.


AFSCM
Android

development guidelines
v1.0
.1

p
27
/
36


Copyright © AFSCM
2011

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
75
:

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


2.11

Protection of the
E
nvironment

The security of mobile applications does not only concern 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 protocols.

Thus,
the
application
s

are not only the direct target of the attacks: they could be used as
co
mmunication 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
76
:
The appl
ication shall not send any executable program to remote entities.

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

.bat, .sh, .pif
.


Rule
77
:
Executable code in SMS/MMS binary messages is forbidden.

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


Rule
78
:
The application 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 operations.



AFSCM
Android

development guidelines
v1.0
.1

p
28
/
36


Copyright © AFSCM
2011

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 proprietary 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獴sb攠p牯v楤敤

X



Rule
7
:
The list o
f 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 o
n 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 description of copying, storing and transferring personal dat
a 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



Ru
le
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 handl
ed

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 sepa
ration

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 defaul
t rule

X



Rule
23
:
Writing in system output streams shall be prohibited

X



Rule
24
:

The mobile application 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.0
.1

p
29
/
36


Copyright © AFSCM
2011

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 applicat
ions as there are MNO supported.

X



Rule
26
:

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


X


Rule
27
:

When publishing an update to its application, the SP should 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

fo
llowing

items
must

be declared
in the
AndroidManifest.xml

file:

X



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


X


Rule
31
:
The developer must specify
<data>

elements in the
AndroidManifest.xml

along with this intent to correctly handle NFC tags that
sta
rt this intent.

X



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

intent in your
AndroidManifest.xml

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

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 nee
ded 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

Rule
38
:
The Activity that is pushing the data must be in the foreground

X



Rule
39
:
The developer must encapsulate the data that he/she is sending in an
NdefMess
age

object

X



Rule
40
:
The NFC device that is receiving the pushed data (the scanned device) must
support the
com.android.npp

NDEF push protocol, which is optional for Android
devices.

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



UPI
and SP
App

Interco
nnecti
on

Rule
42
:
The
following metadata
must

be declared in the
AndroidManifest.xml

file

to ensure
UPI
interconnection
:

X




AFSCM
Android

development guidelines
v1.0
.1

p
30
/
36


Copyright © AFSCM
2011

Section

Rule

ID and

description

Mandatory

Recommended

Information

Rule
43
:
UPI interconnection metadata

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

X



Rule
44
:
NFC
-
App
-
Name

and
NFC
-
app
-
Vendor

must

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

X



Connectivity

Rule
45
:
The

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

X



Rule
46
:

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

X



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

X



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


X


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


X


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


X


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


X


Security requirements

Rule
52
:
Regarding the mandatory
Android

and
Open Mobile

API
s
, the following
permissions
should

be requested by SP
applications
:



X

Rule
53
:
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.SMART
CARD

and

org.simalliance.openmobileapi.SMARTCARD

permissions
)


X


Rule
54
: In order to make the application installable and visible on the market only
to handsets supporting the Open Mobile APIs, the Android Manifest.xml must
contain the

following line:

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

X



Rule
55
:
The application
must
not access any
no
n
-
public
resources

of other
applications
.

X



Rule
56
:
The application
must

not access
the user’s MSISDN
.

X



Rule
57
:
Explicit usage of garbage collection is strongly discouraged.


X


Rule
58
:
The application must not alter personal information

X



Rule
59
:
The application verifies the consistency of its
database


X


Rule
60
:
The application should p
erform
verification to preserve sy
stem integrity


X


Rule
61
:
The application should

preserve RFID tags integri
ty


X


Rule
62
:
The application verifies the consistency of its files


X


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


X


Rule
64
:
App
lication’s secrets are not hard coded plaintext in the code.


X


Rule
65
:
Secrets are not stored as plaintext.

X



Rule
66
:
Avoid decrypting secrets for comparison.

X



Rule
67
:
The appl
ication does not send Operator and third party data.

X



Rule
68
:
The application does not send device localization data

(without end user
approval)
.

X



Rule
69
:

The application does not send identification da
ta

(without end user
approval)
.

X



Rule
70
:
The application does not send device configurati
on data

(without end user
approval)
.

X



Rule
71
:
The application ensures personal data cannot be exploited remotely

X




AFSCM
Android

development guidelines
v1.0
.1

p
31
/
36


Copyright © AFSCM
2011

Section

Rule

ID and

description

Mandatory

Recommended

Information

(without end user approval)
.

Rule
72
:
The application implements mutual authentication mechanisms.


X


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


X


Rule
74
:
The application uses encrypted communications.


X


Rule
75
:

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

X



Environment
protection

Rule
76
:
The appl
ication shall not send any executable program to remote entities.

X



Rule
77
:
Executable code in SMS/MMS binary messages is forbidden.

X



Rule
78
:
The application 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 application 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 applica
tion 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:

<uses
-
sdk android:minSdkVersion="9"/>
, which indicates to Android Market and the
plat
form 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 version="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.

--
>


<!
--

Declare the contents of this Android application. The namespace


attribute brings in the Android platform namespace, and the package


su
pplies 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.
--
>


AFSCM
Android

development guidelines
v1.0
.1

p
32
/
36


Copyright © AFSCM
2011

<manifest xmlns:android="http://schemas.android.com/a
pk/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"


androi
d:label="@string/app_name"


>


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


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


<intent
-
filter>


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


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


</intent
-
filter>


</activity>


<activity android:name="TagViewer"


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


>


<intent
-
filter>


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


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


</intent
-
filter>


</activity>


</application>


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


<uses
-
featu
re 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 <p
roject
-
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.MifareClassic</tech>


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


</tech
-
list>

</resources>


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
t
echnologies that are returned by getTechList(). This provides AND and OR semantics for matching

AFSCM
Android

development guidelines
v1.0
.1

p
33
/
36


Copyright © AFSCM
2011

technologies. The following example matches tags that can support the NfcA and Ndef
technologies or can support the NfcB and Ndef technologies:


<resources xmln
s: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:xliff="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 file 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="android.nfc.action.TECH_DISCOVERED"


androi
d: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 PendingIntent object so the Android system can pop
ulate 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 han
dle 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 handles the
intent. If it does not m
atch, 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 han
dles 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 e) {


throw new RuntimeException("fail", e)
;

}

intentFiltersArray = new IntentFilter[] {ndef};



AFSCM
Android

development guidelines
v1.0
.1

p
34
/
36


Copyright © AFSCM
2011

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 technology that
the
developer

want to support.

techListsArray =

new String[][] { new String[] { NfcF.class.getName() } };


2.


Override the following Activity lifecycle callbacks and add logic to enable and disable the
foreground dispatch when the Activity loses (onPause()) and regains (onResume()) focus.
enableForegroun
dDispatch(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 pr
ocess
the data from the scanned NFC tag.

public void onPause() {


super.onPause();


mAdapter.disableForegroundDispatch(this);

}


public void onResume() {


super.onResume();


mAdapter.enableForegroundDispatch(this, pendingIntent, intentFiltersAr
ray,
techListsArray);

}


public void onNewIntent(Intent intent) {


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


//do something with tagFromIntent

}


4.1.4

Using Smart Card
-
based features

4.1.4.1

Usage pattern

The usage pattern of the API i
s 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 establi
shed. 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 available readers. Readers are the slots where SEs are
connected (in a removable or no
n 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 application can retrieve the ATR of the SE, and if it matches with one of
the

known A
TRs, 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 the newly opened channel.

5.

Then the terminal application can start transmitting AP
DUs 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.4.2

Sample code

-

Initialize the
Secure Element

Access

o

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

method, add

try

{


SEServiceCallback callback = new SEServiceCallback();


seService

=

new

SEService

(
this
,

callback
);

}

catch

(
SecurityException

se
e
x
)

{


AFSCM
Android

development guidelines
v1.0
.1

p
35
/
36


Copyright © AFSCM
2011



Log
.
e
(
LOG_TAG
,

"Binding not allowed, SMARTCARD permission?"
);

}

catch

(
Exception

e
x
)

{



Log
.
e
(
L
OG_TAG
,

"Exception: "

+

e
x
.
getMessage
());

}

o

create a
SEService

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 sy
stem and it's resources.

*/

public class SEServiceCallback implements CallBack {



/**


* This method will be called if this SEService is connected


*/


public void serviceConnected(SEService service) {


try {


performsOperations(servi
ce);


} catch (Exception ex) {


printException(ex);


}


}

}



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 in
itialize
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 reque
sts 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"/>


-

Accessing the Smart Card

voi
d performsOperations(SEService service) throws Exception{


Readers[] readers;


int readerIndex;


SESession seSession;


Channel

se
Channel
;


this.seService = service;


try

{



readers = seService.getReaders();



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



if(readers[i].getName.e
quals(“Mobile Security Card” &&

readers[i].isSecureElementPresent()){


readerIndex =
i;



}



}



session = readers[readerIndex].openSession();




se
Channel
=

seSession
.
openLogicalChannel
(





new

byte
[]

{

(
byte
)
0xD2
,

0x76
,

0x00
,

0x01
,

0x18
,

0x00
,

0x02
,




















(
byte
)
0xFF
,

0x49
,

0x50
,

0x25
,

(
byte
)
0x89
,




















(
byte
)
0xC0
,

0x01
,

(
byte
)
0x9B
,

0x01
});





byte
[]

respApdu
=

se
Channel
.
transmit
(


AFSCM
Android

development guidelines
v1.0
.1

p
36
/
36


Copyright © AFSCM
2011










new

byte
[]

{(
b
yte
)
0x90
,

0x10
,

0x00
,

0x00
,

0x00

});




se
Channel
.
close
();



readers[
readerIndex
].closeSession();




byte
[]

helloStr
=

new

byte
[
respApdu
.
length
-

2
];




System
.
arraycopy
(
respApdu
,

0
,

helloStr
,

0
,

respApdu
.
length
-

2
);



}

catch

(
CardException

e
x
)

{


printException(ex);




return
;


}

}

In this code, a logical channel to the applet identified by its AID D2 76 00 01 18 00 02 FF 49 50
25 89 C0 01 9B 01 is created. The applet specific APDU command 90 10 00 00 00 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.


-

Closing the SmartCard Access

o

To clean up the service binding, call the
shutdown method 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
.
shutdown
();



}




super
.
onDestroy
();

}

-

Example 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"


...


<activity android:name="<Act
ivityName>"



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


</activity>


...


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

</manifest>



-

Others full examples can be fou
nd 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)




END OF DOCUMENT