public class MqttService extends android.app.Service implements MqttTraceHandler
The android service which interfaces with an MQTT client implementation
The main API of MqttService is intended to pretty much mirror the
IMqttAsyncClient with appropriate adjustments for the Android environment.
These adjustments usually consist of adding two parameters to each method :-
To support multiple client connections, the bulk of the MQTT work is delegated to MqttConnection objects. These are identified by "client handle" strings, which is how the Activity, and the higher-level APIs refer to them.
Activities using this service are expected to start it and bind to it using the BIND_AUTO_CREATE flag. The life cycle of this service is based on this approach.
Operations are highly asynchronous - in most cases results are returned to
the Activity by broadcasting one (or occasionally more) appropriate Intents,
which the Activity is expected to register a listener for.
The Intents have an Action of
MqttServiceConstants.CALLBACK_TO_ACTIVITY which allows the Activity to
register a listener with an appropriate IntentFilter.
Further data is provided by "Extra Data" in the Intent, as follows :-
| Name | Data Type | Value | Operations used for | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
MqttServiceConstants.CALLBACK_CLIENT_HANDLE |
String | The clientHandle identifying the client which initiated this operation | All operations | ||||||||
MqttServiceConstants.CALLBACK_STATUS |
Serializable | An Status value indicating success or
otherwise of the operation |
All operations | ||||||||
MqttServiceConstants.CALLBACK_ACTIVITY_TOKEN |
String | the activityToken passed into the operation | All operations | ||||||||
MqttServiceConstants.CALLBACK_INVOCATION_CONTEXT |
String | the invocationContext passed into the operation | All operations | ||||||||
MqttServiceConstants.CALLBACK_ACTION |
String | one of
|
All operations | ||||||||
MqttServiceConstants.CALLBACK_ERROR_MESSAGE
| String | A suitable error message (taken from the relevant exception where possible) | All failing operations | ||||||||
MqttServiceConstants.CALLBACK_ERROR_NUMBER
| int | A suitable error code (taken from the relevant exception where possible) | All failing operations | ||||||||
MqttServiceConstants.CALLBACK_EXCEPTION_STACK |
String | The stacktrace of the failing call | The Connection Lost event | ||||||||
MqttServiceConstants.CALLBACK_MESSAGE_ID |
String | The identifier for the message in the message store, used by the Activity to acknowledge the arrival of the message, so that the service may remove it from the store | The Message Arrived event | ||||||||
MqttServiceConstants.CALLBACK_DESTINATION_NAME
| String | The topic on which the message was received | The Message Arrived event | ||||||||
MqttServiceConstants.CALLBACK_MESSAGE_PARCEL |
Parcelable | The new message encapsulated in Android
Parcelable format as a ParcelableMqttMessage |
The Message Arrived event |
START_CONTINUATION_MASK, START_FLAG_REDELIVERY, START_FLAG_RETRY, START_NOT_STICKY, START_REDELIVER_INTENT, START_STICKY, START_STICKY_COMPATIBILITY, STOP_FOREGROUND_DETACH, STOP_FOREGROUND_REMOVEACCESSIBILITY_SERVICE, ACCOUNT_SERVICE, ACTIVITY_SERVICE, ALARM_SERVICE, APP_OPS_SERVICE, APPWIDGET_SERVICE, AUDIO_SERVICE, BATTERY_SERVICE, BIND_ABOVE_CLIENT, BIND_ADJUST_WITH_ACTIVITY, BIND_ALLOW_OOM_MANAGEMENT, BIND_AUTO_CREATE, BIND_DEBUG_UNBIND, BIND_EXTERNAL_SERVICE, BIND_IMPORTANT, BIND_NOT_FOREGROUND, BIND_WAIVE_PRIORITY, BLUETOOTH_SERVICE, CAMERA_SERVICE, CAPTIONING_SERVICE, CARRIER_CONFIG_SERVICE, CLIPBOARD_SERVICE, CONNECTIVITY_SERVICE, CONSUMER_IR_SERVICE, CONTEXT_IGNORE_SECURITY, CONTEXT_INCLUDE_CODE, CONTEXT_RESTRICTED, DEVICE_POLICY_SERVICE, DISPLAY_SERVICE, DOWNLOAD_SERVICE, DROPBOX_SERVICE, FINGERPRINT_SERVICE, HARDWARE_PROPERTIES_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_STATS_SERVICE, NFC_SERVICE, NOTIFICATION_SERVICE, NSD_SERVICE, POWER_SERVICE, PRINT_SERVICE, RESTRICTIONS_SERVICE, SEARCH_SERVICE, SENSOR_SERVICE, STORAGE_SERVICE, SYSTEM_HEALTH_SERVICE, TELECOM_SERVICE, TELEPHONY_SERVICE, TELEPHONY_SUBSCRIPTION_SERVICE, TEXT_SERVICES_MANAGER_SERVICE, TV_INPUT_SERVICE, UI_MODE_SERVICE, USAGE_STATS_SERVICE, USB_SERVICE, USER_SERVICE, VIBRATOR_SERVICE, WALLPAPER_SERVICE, WIFI_P2P_SERVICE, WIFI_SERVICE, WINDOW_SERVICE| Constructor and Description |
|---|
MqttService() |
| Modifier and Type | Method and Description |
|---|---|
org.eclipse.paho.android.service.Status |
acknowledgeMessageArrival(java.lang.String clientHandle,
java.lang.String id)
Called by the Activity when a message has been passed back to the
application
|
void |
close(java.lang.String clientHandle)
Close connection from a particular client
|
void |
connect(java.lang.String clientHandle,
org.eclipse.paho.client.mqttv3.MqttConnectOptions connectOptions,
java.lang.String invocationContext,
java.lang.String activityToken)
Connect to the MQTT server specified by a particular client
|
void |
deleteBufferedMessage(java.lang.String clientHandle,
int bufferIndex) |
void |
disconnect(java.lang.String clientHandle,
long quiesceTimeout,
java.lang.String invocationContext,
java.lang.String activityToken)
Disconnect from the server
|
void |
disconnect(java.lang.String clientHandle,
java.lang.String invocationContext,
java.lang.String activityToken)
Disconnect from the server
|
org.eclipse.paho.client.mqttv3.MqttMessage |
getBufferedMessage(java.lang.String clientHandle,
int bufferIndex) |
int |
getBufferedMessageCount(java.lang.String clientHandle) |
java.lang.String |
getClient(java.lang.String serverURI,
java.lang.String clientId,
java.lang.String contextId,
org.eclipse.paho.client.mqttv3.MqttClientPersistence persistence)
Get an MqttConnection object to represent a connection to a server
|
org.eclipse.paho.client.mqttv3.IMqttDeliveryToken[] |
getPendingDeliveryTokens(java.lang.String clientHandle)
Get tokens for all outstanding deliveries for a client
|
boolean |
isConnected(java.lang.String clientHandle)
Get the status of a specific client
|
boolean |
isOnline() |
boolean |
isTraceEnabled()
Check whether trace is on or off.
|
android.os.IBinder |
onBind(android.content.Intent intent) |
void |
onCreate() |
void |
onDestroy() |
int |
onStartCommand(android.content.Intent intent,
int flags,
int startId) |
org.eclipse.paho.client.mqttv3.IMqttDeliveryToken |
publish(java.lang.String clientHandle,
java.lang.String topic,
byte[] payload,
int qos,
boolean retained,
java.lang.String invocationContext,
java.lang.String activityToken)
Publish a message to a topic
|
org.eclipse.paho.client.mqttv3.IMqttDeliveryToken |
publish(java.lang.String clientHandle,
java.lang.String topic,
org.eclipse.paho.client.mqttv3.MqttMessage message,
java.lang.String invocationContext,
java.lang.String activityToken)
Publish a message to a topic
|
void |
setBufferOpts(java.lang.String clientHandle,
org.eclipse.paho.client.mqttv3.DisconnectedBufferOptions bufferOpts)
Sets the DisconnectedBufferOptions for this client
|
void |
setTraceCallbackId(java.lang.String traceCallbackId)
Identify the callbackId to be passed when making tracing calls back into
the Activity
|
void |
setTraceEnabled(boolean traceEnabled)
Turn tracing on and off
|
void |
subscribe(java.lang.String clientHandle,
java.lang.String[] topic,
int[] qos,
java.lang.String invocationContext,
java.lang.String activityToken)
Subscribe to one or more topics
|
void |
subscribe(java.lang.String clientHandle,
java.lang.String[] topicFilters,
int[] qos,
java.lang.String invocationContext,
java.lang.String activityToken,
org.eclipse.paho.client.mqttv3.IMqttMessageListener[] messageListeners)
Subscribe using topic filters
|
void |
subscribe(java.lang.String clientHandle,
java.lang.String topic,
int qos,
java.lang.String invocationContext,
java.lang.String activityToken)
Subscribe to a topic
|
void |
traceDebug(java.lang.String tag,
java.lang.String message)
Trace debugging information
|
void |
traceError(java.lang.String tag,
java.lang.String message)
Trace error information
|
void |
traceException(java.lang.String tag,
java.lang.String message,
java.lang.Exception e)
trace exceptions
|
void |
unsubscribe(java.lang.String clientHandle,
java.lang.String[] topic,
java.lang.String invocationContext,
java.lang.String activityToken)
Unsubscribe from one or more topics
|
void |
unsubscribe(java.lang.String clientHandle,
java.lang.String topic,
java.lang.String invocationContext,
java.lang.String activityToken)
Unsubscribe from a topic
|
dump, getApplication, onConfigurationChanged, onLowMemory, onRebind, onStart, onTaskRemoved, onTrimMemory, onUnbind, startForeground, stopForeground, stopForeground, stopSelf, stopSelf, stopSelfResultattachBaseContext, bindService, checkCallingOrSelfPermission, checkCallingOrSelfUriPermission, checkCallingPermission, checkCallingUriPermission, checkPermission, checkSelfPermission, checkUriPermission, checkUriPermission, clearWallpaper, createConfigurationContext, createDeviceProtectedStorageContext, createDisplayContext, createPackageContext, databaseList, deleteDatabase, deleteFile, deleteSharedPreferences, enforceCallingOrSelfPermission, enforceCallingOrSelfUriPermission, enforceCallingPermission, enforceCallingUriPermission, enforcePermission, enforceUriPermission, enforceUriPermission, fileList, getApplicationContext, getApplicationInfo, getAssets, getBaseContext, getCacheDir, getClassLoader, getCodeCacheDir, getContentResolver, getDatabasePath, getDataDir, getDir, getExternalCacheDir, getExternalCacheDirs, getExternalFilesDir, getExternalFilesDirs, getExternalMediaDirs, getFilesDir, getFileStreamPath, getMainLooper, getNoBackupFilesDir, getObbDir, getObbDirs, getPackageCodePath, getPackageManager, getPackageName, getPackageResourcePath, getResources, getSharedPreferences, getSystemService, getSystemServiceName, getTheme, getWallpaper, getWallpaperDesiredMinimumHeight, getWallpaperDesiredMinimumWidth, grantUriPermission, isDeviceProtectedStorage, isRestricted, moveDatabaseFrom, moveSharedPreferencesFrom, openFileInput, openFileOutput, openOrCreateDatabase, openOrCreateDatabase, peekWallpaper, registerReceiver, registerReceiver, removeStickyBroadcast, removeStickyBroadcastAsUser, revokeUriPermission, sendBroadcast, sendBroadcast, sendBroadcastAsUser, sendBroadcastAsUser, sendOrderedBroadcast, sendOrderedBroadcast, sendOrderedBroadcastAsUser, sendStickyBroadcast, sendStickyBroadcastAsUser, sendStickyOrderedBroadcast, sendStickyOrderedBroadcastAsUser, setTheme, setWallpaper, setWallpaper, startActivities, startActivities, startActivity, startActivity, startInstrumentation, startIntentSender, startIntentSender, startService, stopService, unbindService, unregisterReceiverpublic java.lang.String getClient(java.lang.String serverURI,
java.lang.String clientId,
java.lang.String contextId,
org.eclipse.paho.client.mqttv3.MqttClientPersistence persistence)
serverURI - specifies the protocol, host name and port to be used to connect to an MQTT serverclientId - specifies the name by which this connection should be identified to the servercontextId - specifies the app conext info to make a difference between appspersistence - specifies the persistence layer to be used with this clientpublic void connect(java.lang.String clientHandle,
org.eclipse.paho.client.mqttv3.MqttConnectOptions connectOptions,
java.lang.String invocationContext,
java.lang.String activityToken)
throws org.eclipse.paho.client.mqttv3.MqttSecurityException,
org.eclipse.paho.client.mqttv3.MqttException
clientHandle - identifies the MqttConnection to useconnectOptions - the MQTT connection options to be usedinvocationContext - arbitrary data to be passed back to the applicationactivityToken - arbitrary identifier to be passed back to the Activityorg.eclipse.paho.client.mqttv3.MqttSecurityException - thrown if there is a security exceptionorg.eclipse.paho.client.mqttv3.MqttException - thrown for all other MqttExceptionspublic void close(java.lang.String clientHandle)
clientHandle - identifies the MqttConnection to usepublic void disconnect(java.lang.String clientHandle,
java.lang.String invocationContext,
java.lang.String activityToken)
clientHandle - identifies the MqttConnection to useinvocationContext - arbitrary data to be passed back to the applicationactivityToken - arbitrary identifier to be passed back to the Activitypublic void disconnect(java.lang.String clientHandle,
long quiesceTimeout,
java.lang.String invocationContext,
java.lang.String activityToken)
clientHandle - identifies the MqttConnection to usequiesceTimeout - in millisecondsinvocationContext - arbitrary data to be passed back to the applicationactivityToken - arbitrary identifier to be passed back to the Activitypublic boolean isConnected(java.lang.String clientHandle)
clientHandle - identifies the MqttConnection to usepublic org.eclipse.paho.client.mqttv3.IMqttDeliveryToken publish(java.lang.String clientHandle,
java.lang.String topic,
byte[] payload,
int qos,
boolean retained,
java.lang.String invocationContext,
java.lang.String activityToken)
throws org.eclipse.paho.client.mqttv3.MqttPersistenceException,
org.eclipse.paho.client.mqttv3.MqttException
clientHandle - identifies the MqttConnection to usetopic - the topic to which to publishpayload - the content of the message to publishqos - the quality of service requestedretained - whether the MQTT server should retain this messageinvocationContext - arbitrary data to be passed back to the applicationactivityToken - arbitrary identifier to be passed back to the Activityorg.eclipse.paho.client.mqttv3.MqttPersistenceException - when a problem occurs storing the messageorg.eclipse.paho.client.mqttv3.MqttException - if there was an error publishing the messagepublic org.eclipse.paho.client.mqttv3.IMqttDeliveryToken publish(java.lang.String clientHandle,
java.lang.String topic,
org.eclipse.paho.client.mqttv3.MqttMessage message,
java.lang.String invocationContext,
java.lang.String activityToken)
throws org.eclipse.paho.client.mqttv3.MqttPersistenceException,
org.eclipse.paho.client.mqttv3.MqttException
clientHandle - identifies the MqttConnection to usetopic - the topic to which to publishmessage - the message to publishinvocationContext - arbitrary data to be passed back to the applicationactivityToken - arbitrary identifier to be passed back to the Activityorg.eclipse.paho.client.mqttv3.MqttPersistenceException - when a problem occurs storing the messageorg.eclipse.paho.client.mqttv3.MqttException - if there was an error publishing the messagepublic void subscribe(java.lang.String clientHandle,
java.lang.String topic,
int qos,
java.lang.String invocationContext,
java.lang.String activityToken)
clientHandle - identifies the MqttConnection to usetopic - a possibly wildcarded topic nameqos - requested quality of service for the topicinvocationContext - arbitrary data to be passed back to the applicationactivityToken - arbitrary identifier to be passed back to the Activitypublic void subscribe(java.lang.String clientHandle,
java.lang.String[] topic,
int[] qos,
java.lang.String invocationContext,
java.lang.String activityToken)
clientHandle - identifies the MqttConnection to usetopic - a list of possibly wildcarded topic namesqos - requested quality of service for each topicinvocationContext - arbitrary data to be passed back to the applicationactivityToken - arbitrary identifier to be passed back to the Activitypublic void subscribe(java.lang.String clientHandle,
java.lang.String[] topicFilters,
int[] qos,
java.lang.String invocationContext,
java.lang.String activityToken,
org.eclipse.paho.client.mqttv3.IMqttMessageListener[] messageListeners)
clientHandle - identifies the MqttConnection to usetopicFilters - a list of possibly wildcarded topicfiltersqos - requested quality of service for each topicinvocationContext - arbitrary data to be passed back to the applicationactivityToken - arbitrary identifier to be passed back to the ActivitymessageListeners - a callback to handle incoming messagespublic void unsubscribe(java.lang.String clientHandle,
java.lang.String topic,
java.lang.String invocationContext,
java.lang.String activityToken)
clientHandle - identifies the MqttConnectiontopic - a possibly wildcarded topic nameinvocationContext - arbitrary data to be passed back to the applicationactivityToken - arbitrary identifier to be passed back to the Activitypublic void unsubscribe(java.lang.String clientHandle,
java.lang.String[] topic,
java.lang.String invocationContext,
java.lang.String activityToken)
clientHandle - identifies the MqttConnectiontopic - a list of possibly wildcarded topic namesinvocationContext - arbitrary data to be passed back to the applicationactivityToken - arbitrary identifier to be passed back to the Activitypublic org.eclipse.paho.client.mqttv3.IMqttDeliveryToken[] getPendingDeliveryTokens(java.lang.String clientHandle)
clientHandle - identifies the MqttConnectionpublic org.eclipse.paho.android.service.Status acknowledgeMessageArrival(java.lang.String clientHandle,
java.lang.String id)
clientHandle - identifier for the client which received the messageid - identifier for the MQTT messageStatuspublic void onCreate()
onCreate in class android.app.ServiceService.onCreate()public void onDestroy()
onDestroy in class android.app.ServiceService.onDestroy()public android.os.IBinder onBind(android.content.Intent intent)
onBind in class android.app.ServiceService.onBind(Intent)public int onStartCommand(android.content.Intent intent,
int flags,
int startId)
onStartCommand in class android.app.ServiceService.onStartCommand(Intent,int,int)public void setTraceCallbackId(java.lang.String traceCallbackId)
traceCallbackId - identifier to the callback into the Activitypublic void setTraceEnabled(boolean traceEnabled)
traceEnabled - set true to turn on tracing, false to turn off tracingpublic boolean isTraceEnabled()
public void traceDebug(java.lang.String tag,
java.lang.String message)
traceDebug in interface MqttTraceHandlertag - identifier for the source of the tracemessage - the text to be tracedpublic void traceError(java.lang.String tag,
java.lang.String message)
traceError in interface MqttTraceHandlertag - identifier for the source of the tracemessage - the text to be tracedpublic void traceException(java.lang.String tag,
java.lang.String message,
java.lang.Exception e)
traceException in interface MqttTraceHandlertag - identifier for the source of the tracemessage - the text to be tracede - the exceptionpublic boolean isOnline()
public void setBufferOpts(java.lang.String clientHandle,
org.eclipse.paho.client.mqttv3.DisconnectedBufferOptions bufferOpts)
clientHandle - identifier for the clientbufferOpts - the DisconnectedBufferOptions for this clientpublic int getBufferedMessageCount(java.lang.String clientHandle)
public org.eclipse.paho.client.mqttv3.MqttMessage getBufferedMessage(java.lang.String clientHandle,
int bufferIndex)
public void deleteBufferedMessage(java.lang.String clientHandle,
int bufferIndex)