public abstract class HostApduService extends Service
HostApduService is a convenience Service
class that can be
extended to emulate an NFC card inside an Android
service component.
Cards emulated by this class are based on the NFC-Forum ISO-DEP protocol (based on ISO/IEC 14443-4) and support processing command Application Protocol Data Units (APDUs) as defined in the ISO/IEC 7816-4 specification.
When a remote NFC device wants to talk to your service, it sends a so-called "SELECT AID" APDU as defined in the ISO/IEC 7816-4 specification. The AID is an application identifier defined in ISO/IEC 7816-4.
The registration procedure for AIDs is defined in the ISO/IEC 7816-5 specification. If you don't want to register an AID, you are free to use AIDs in the proprietary range: bits 8-5 of the first byte must each be set to '1'. For example, "0xF00102030405" is a proprietary AID. If you do use proprietary AIDs, it is recommended to choose an AID of at least 6 bytes, to reduce the risk of collisions with other applications that might be using proprietary AIDs as well.
In some cases, a service may need to register multiple AIDs to implement a certain application, and it needs to be sure that it is the default handler for all of these AIDs (as opposed to some AIDs in the group going to another service).
An AID group is a list of AIDs that should be considered as belonging together by the OS. For all AIDs in an AID group, the OS will guarantee one of the following:
Each AID group can be associated with a category. This allows the Android OS to classify services, and it allows the user to set defaults at the category level instead of the AID level.
You can use
CardEmulation.isDefaultServiceForCategory(android.content.ComponentName, String)
to determine if your service is the default handler for a category.
In this version of the platform, the only known categories
are CardEmulation.CATEGORY_PAYMENT
and CardEmulation.CATEGORY_OTHER
.
AID groups without a category, or with a category that is not recognized
by the current platform version, will automatically be
grouped into the CardEmulation.CATEGORY_OTHER
category.
To tell the platform which AIDs groups
are requested by this service, a SERVICE_META_DATA
entry must be included in the declaration of the service. An
example of a HostApduService manifest declaration is shown below:
<service android:name=".MyHostApduService" android:exported="true" android:permission="android.permission.BIND_NFC_SERVICE"> <intent-filter> <action android:name="android.nfc.cardemulation.action.HOST_APDU_SERVICE"/> </intent-filter> <meta-data android:name="android.nfc.cardemulation.host_apdu_ervice" android:resource="@xml/apduservice"/> </service>This meta-data tag points to an apduservice.xml file. An example of this file with a single AID group declaration is shown below:
<host-apdu-service xmlns:android="http://schemas.android.com/apk/res/android" android:description="@string/servicedesc" android:requireDeviceUnlock="false"> <aid-group android:description="@string/aiddescription" android:category="other"> <aid-filter android:name="F0010203040506"/> <aid-filter android:name="F0394148148100"/> </aid-group> </host-apdu-service>
The <host-apdu-service>
is required
to contain a
<android:description>
attribute that contains a user-friendly description of the service that may be shown in UI.
The
<requireDeviceUnlock>
attribute can be used to specify that the device must be unlocked before this service
can be invoked to handle APDUs.
The <host-apdu-service>
must
contain one or more <aid-group>
tags.
Each <aid-group>
must contain one or
more <aid-filter>
tags, each of which
contains a single AID. The AID must be specified in hexadecimal format, and contain
an even number of characters.
CardEmulation.getSelectionModeForCategory(String)
.
Once the platform has resolved a "SELECT AID" command APDU to a specific
service component, the "SELECT AID" command APDU and all subsequent
command APDUs will be sent to that service through
processCommandApdu(byte[], Bundle)
, until either:
onDeactivated(int)
.
Use of this class requires the
PackageManager.FEATURE_NFC_HOST_CARD_EMULATION
to be present
on the device.
Service.StartArgFlags, Service.StartResult, Service.StopForegroundFlags
Context.BindServiceFlags, Context.CreatePackageOptions, Context.ServiceName
Modifier and Type | Field and Description |
---|---|
static int |
DEACTIVATION_DESELECTED
Reason for
onDeactivated(int) . |
static int |
DEACTIVATION_LINK_LOSS
Reason for
onDeactivated(int) . |
static String |
KEY_DATA |
static int |
MSG_COMMAND_APDU
MSG_COMMAND_APDU is sent by NfcService when
a 7816-4 command APDU has been received.
|
static int |
MSG_DEACTIVATED
MSG_DEACTIVATED is sent by NfcService when
the current session is finished; either because
another AID was selected that resolved to
another service, or because the NFC link
was deactivated.
|
static int |
MSG_RESPONSE_APDU
MSG_RESPONSE_APDU is sent to NfcService to send
a response APDU back to the remote device.
|
static int |
MSG_UNHANDLED |
static String |
SERVICE_INTERFACE
The
Intent action that must be declared as handled by the service. |
static String |
SERVICE_META_DATA
The name of the meta-data element that contains
more information about this service.
|
START_CONTINUATION_MASK, START_FLAG_REDELIVERY, START_FLAG_RETRY, START_NOT_STICKY, START_REDELIVER_INTENT, START_STICKY, START_STICKY_COMPATIBILITY, START_TASK_REMOVED_COMPLETE, STOP_FOREGROUND_DETACH, STOP_FOREGROUND_REMOVE
ACCESSIBILITY_SERVICE, ACCOUNT_SERVICE, ACTIVITY_SERVICE, ALARM_SERVICE, APP_OPS_SERVICE, APPWIDGET_SERVICE, AUDIO_SERVICE, BACKUP_SERVICE, BATTERY_SERVICE, BIND_ABOVE_CLIENT, BIND_ADJUST_WITH_ACTIVITY, BIND_ALLOW_OOM_MANAGEMENT, BIND_ALLOW_WHITELIST_MANAGEMENT, BIND_AUTO_CREATE, BIND_DEBUG_UNBIND, BIND_EXTERNAL_SERVICE, BIND_FOREGROUND_SERVICE, BIND_FOREGROUND_SERVICE_WHILE_AWAKE, BIND_IMPORTANT, BIND_NOT_FOREGROUND, BIND_NOT_VISIBLE, BIND_SHOWING_UI, BIND_TREAT_LIKE_ACTIVITY, BIND_VISIBLE, BIND_WAIVE_PRIORITY, BLUETOOTH_SERVICE, CAMERA_SERVICE, CAPTIONING_SERVICE, CARRIER_CONFIG_SERVICE, CLIPBOARD_SERVICE, CONNECTIVITY_SERVICE, CONSUMER_IR_SERVICE, CONTEXT_CREDENTIAL_PROTECTED_STORAGE, CONTEXT_DEVICE_PROTECTED_STORAGE, CONTEXT_IGNORE_SECURITY, CONTEXT_INCLUDE_CODE, CONTEXT_REGISTER_PACKAGE, CONTEXT_RESTRICTED, CONTEXTHUB_SERVICE, COUNTRY_DETECTOR, DEVICE_IDLE_CONTROLLER, DEVICE_POLICY_SERVICE, DISPLAY_SERVICE, DOWNLOAD_SERVICE, DROPBOX_SERVICE, ETHERNET_SERVICE, FINGERPRINT_SERVICE, GATEKEEPER_SERVICE, HARDWARE_PROPERTIES_SERVICE, HDMI_CONTROL_SERVICE, INPUT_METHOD_SERVICE, INPUT_SERVICE, JOB_SCHEDULER_SERVICE, KEYGUARD_SERVICE, LAUNCHER_APPS_SERVICE, LAYOUT_INFLATER_SERVICE, LOCATION_SERVICE, MEDIA_PROJECTION_SERVICE, MEDIA_ROUTER_SERVICE, MEDIA_SESSION_SERVICE, MIDI_SERVICE, MODE_APPEND, MODE_ENABLE_WRITE_AHEAD_LOGGING, MODE_MULTI_PROCESS, MODE_NO_LOCALIZED_COLLATORS, MODE_PRIVATE, MODE_WORLD_READABLE, MODE_WORLD_WRITEABLE, NETWORK_POLICY_SERVICE, NETWORK_SCORE_SERVICE, NETWORK_STATS_SERVICE, NETWORKMANAGEMENT_SERVICE, NFC_SERVICE, NOTIFICATION_SERVICE, NSD_SERVICE, PERSISTENT_DATA_BLOCK_SERVICE, POWER_SERVICE, PRINT_SERVICE, RADIO_SERVICE, RECOVERY_SERVICE, RESTRICTIONS_SERVICE, SEARCH_SERVICE, SENSOR_SERVICE, SERIAL_SERVICE, SHORTCUT_SERVICE, SIP_SERVICE, SOUND_TRIGGER_SERVICE, STATUS_BAR_SERVICE, STORAGE_SERVICE, SYSTEM_HEALTH_SERVICE, TELECOM_SERVICE, TELEPHONY_SERVICE, TELEPHONY_SUBSCRIPTION_SERVICE, TEXT_SERVICES_MANAGER_SERVICE, TRUST_SERVICE, TV_INPUT_SERVICE, UI_MODE_SERVICE, UPDATE_LOCK_SERVICE, USAGE_STATS_SERVICE, USB_SERVICE, USER_SERVICE, VIBRATOR_SERVICE, VOICE_INTERACTION_MANAGER_SERVICE, WALLPAPER_SERVICE, WIFI_NAN_SERVICE, WIFI_P2P_SERVICE, WIFI_RTT_SERVICE, WIFI_SCANNING_SERVICE, WIFI_SERVICE, WINDOW_SERVICE
TRIM_MEMORY_BACKGROUND, TRIM_MEMORY_COMPLETE, TRIM_MEMORY_MODERATE, TRIM_MEMORY_RUNNING_CRITICAL, TRIM_MEMORY_RUNNING_LOW, TRIM_MEMORY_RUNNING_MODERATE, TRIM_MEMORY_UI_HIDDEN
Constructor and Description |
---|
HostApduService() |
Modifier and Type | Method and Description |
---|---|
void |
notifyUnhandled()
Calling this method allows the service to tell the OS
that it won't be able to complete this transaction -
for example, because it requires data connectivity
that is not present at that moment.
|
IBinder |
onBind(Intent intent)
Return the communication channel to the service.
|
abstract void |
onDeactivated(int reason)
This method will be called in two possible scenarios:
The NFC link has been deactivated or lost
A different AID has been selected and was resolved to a different
service component
|
abstract byte[] |
processCommandApdu(byte[] commandApdu,
Bundle extras)
This method will be called when a command APDU has been received
from a remote device.
|
void |
sendResponseApdu(byte[] responseApdu)
Sends a response APDU back to the remote device.
|
attach, dump, getApplication, onConfigurationChanged, onCreate, onDestroy, onLowMemory, onRebind, onStart, onStartCommand, onTaskRemoved, onTrimMemory, onUnbind, setForeground, startForeground, stopForeground, stopForeground, stopSelf, stopSelf, stopSelfResult
attachBaseContext, bindService, bindServiceAsUser, canStartActivityForResult, checkCallingOrSelfPermission, checkCallingOrSelfUriPermission, checkCallingPermission, checkCallingUriPermission, checkPermission, checkPermission, checkSelfPermission, checkUriPermission, checkUriPermission, checkUriPermission, clearWallpaper, createApplicationContext, createConfigurationContext, createCredentialProtectedStorageContext, createDeviceProtectedStorageContext, createDisplayContext, createPackageContext, createPackageContextAsUser, databaseList, deleteDatabase, deleteFile, deleteSharedPreferences, enforceCallingOrSelfPermission, enforceCallingOrSelfUriPermission, enforceCallingPermission, enforceCallingUriPermission, enforcePermission, enforceUriPermission, enforceUriPermission, fileList, getApplicationContext, getApplicationInfo, getAssets, getBaseContext, getBasePackageName, getCacheDir, getClassLoader, getCodeCacheDir, getContentResolver, getDatabasePath, getDataDir, getDir, getDisplay, getDisplayAdjustments, getExternalCacheDir, getExternalCacheDirs, getExternalFilesDir, getExternalFilesDirs, getExternalMediaDirs, getFilesDir, getFileStreamPath, getMainLooper, getNoBackupFilesDir, getObbDir, getObbDirs, getOpPackageName, getPackageCodePath, getPackageManager, getPackageName, getPackageResourcePath, getResources, getSharedPreferences, getSharedPreferences, getSharedPreferencesPath, getSystemService, getSystemServiceName, getTheme, getThemeResId, getUserId, getWallpaper, getWallpaperDesiredMinimumHeight, getWallpaperDesiredMinimumWidth, grantUriPermission, isCredentialProtectedStorage, isDeviceProtectedStorage, isRestricted, moveDatabaseFrom, moveSharedPreferencesFrom, openFileInput, openFileOutput, openOrCreateDatabase, openOrCreateDatabase, peekWallpaper, registerReceiver, registerReceiver, registerReceiverAsUser, removeStickyBroadcast, removeStickyBroadcastAsUser, revokeUriPermission, sendBroadcast, sendBroadcast, sendBroadcast, sendBroadcast, sendBroadcastAsUser, sendBroadcastAsUser, sendBroadcastAsUser, sendBroadcastMultiplePermissions, sendOrderedBroadcast, sendOrderedBroadcast, sendOrderedBroadcast, sendOrderedBroadcast, sendOrderedBroadcastAsUser, sendOrderedBroadcastAsUser, sendOrderedBroadcastAsUser, sendStickyBroadcast, sendStickyBroadcastAsUser, sendStickyBroadcastAsUser, sendStickyOrderedBroadcast, sendStickyOrderedBroadcastAsUser, setTheme, setWallpaper, setWallpaper, startActivities, startActivities, startActivitiesAsUser, startActivity, startActivity, startActivityAsUser, startActivityAsUser, startActivityForResult, startInstrumentation, startIntentSender, startIntentSender, startService, startServiceAsUser, stopService, stopServiceAsUser, unbindService, unregisterReceiver
bindServiceAsUser, createCredentialEncryptedStorageContext, createDeviceEncryptedStorageContext, getColor, getColorStateList, getDrawable, getSharedPrefsFile, getString, getString, getSystemService, getText, isCredentialEncryptedStorage, isDeviceEncryptedStorage, migrateDatabaseFrom, migrateSharedPreferencesFrom, obtainStyledAttributes, obtainStyledAttributes, obtainStyledAttributes, obtainStyledAttributes, registerComponentCallbacks, unregisterComponentCallbacks
public static final String SERVICE_INTERFACE
Intent
action that must be declared as handled by the service.public static final String SERVICE_META_DATA
public static final int DEACTIVATION_LINK_LOSS
onDeactivated(int)
.
Indicates deactivation was due to the NFC link
being lost.public static final int DEACTIVATION_DESELECTED
onDeactivated(int)
.
Indicates deactivation was due to a different AID being selected (which implicitly deselects the AID currently active on the logical channel).
Note that this next AID may still be resolved to this
service, in which case processCommandApdu(byte[], Bundle)
will be called again.
public static final int MSG_COMMAND_APDU
public static final int MSG_RESPONSE_APDU
public static final int MSG_DEACTIVATED
public static final int MSG_UNHANDLED
public static final String KEY_DATA
public final IBinder onBind(Intent intent)
Service
IBinder
is usually for a complex interface
that has been described using
aidl.
Note that unlike other application components, calls on to the IBinder interface returned here may not happen on the main thread of the process. More information about the main thread can be found in Processes and Threads.
onBind
in class Service
intent
- The Intent that was used to bind to this service,
as given to Context.bindService
. Note that any extras that were included with
the Intent at that point will not be seen here.public final void sendResponseApdu(byte[] responseApdu)
Note: this method may be called from any thread and will not block.
responseApdu
- A byte-array containing the reponse APDU.public final void notifyUnhandled()
Note: this method may be called anywhere between
the first processCommandApdu(byte[], Bundle)
call and a onDeactivated(int)
call.
public abstract byte[] processCommandApdu(byte[] commandApdu, Bundle extras)
This method will be called when a command APDU has been received from a remote device. A response APDU can be provided directly by returning a byte-array in this method. Note that in general response APDUs must be sent as quickly as possible, given the fact that the user is likely holding his device over an NFC reader when this method is called.
If there are multiple services that have registered for the same AIDs in their meta-data entry, you will only get called if the user has explicitly selected your service, either as a default or just for the next tap.
This method is running on the main thread of your application.
If you cannot return a response APDU immediately, return null
and use the sendResponseApdu(byte[])
method later.
commandApdu
- The APDU that was received from the remote deviceextras
- A bundle containing extra data. May be null.public abstract void onDeactivated(int reason)
reason
- Either DEACTIVATION_LINK_LOSS
or DEACTIVATION_DESELECTED