Android SharedPreferences Tutorial and Example

Connecting to IoT devices with the MQTT protocol

Android phones increasingly serve as control panels for connected appliances, environmental sensors, solar installations, irrigation systems and industrial equipment. Connecting to IoT devices with the MQTT protocol gives applications a lightweight way to exchange messages without opening a direct connection to every device on the network.

MQTT uses a publish-and-subscribe model. Devices publish telemetry to named topics, while Android clients subscribe to the topics they need. A central message broker handles routing, which is particularly useful when devices sit behind different Wi-Fi routers, cellular gateways or local radio networks.

Reliable Android implementations must also account for changing mobile connections, background restrictions and sensitive Australian household data. Common Australian use cases include rooftop-solar monitoring in Sydney and Melbourne, supermarket refrigeration telemetry and farm sensors linked through regional gateways.

MQTT Architecture for Android IoT

Each MQTT client has a unique client identifier and connects to a broker over a persistent connection. Devices publish readings such as temperature or battery status, and Android apps publish commands through topics such as home/greenhouse/valve/command. The broker forwards each message to matching subscribers, including wildcard subscriptions such as home/+/telemetry.

Delivery settings determine how messages behave. Quality of Service level 0 suits frequent, disposable sensor readings, while level 1 is safer for commands that should not be lost. Retained messages provide the latest known state when an app subscribes, and a Last Will and Testament publishes an offline status if a device disappears unexpectedly. Keep-alive intervals allow the broker to detect broken connections.

Payloads should remain small and versioned. A useful JSON telemetry message might contain a device identifier, sensor value, unit, timestamp and schema version. This structured format is easier to validate than loosely formatted text and allows an Android application to handle several device types without tying its UI to a particular manufacturer.

Building an Android MQTT Client

Add a maintained Android MQTT client library to the Gradle project. Eclipse Paho Android Service is a common choice because it provides connection callbacks and automatic reconnection support. The client identifier should be stable per installation when persistent sessions are required, while still remaining unique enough to prevent one phone from accidentally taking over another phone’s session.

A Paho connection typically follows this pattern:

val mqttClient = MqttAndroidClient(
    context,
    "ssl://broker.example.com:8883",
    installationClientId
)

val options = MqttConnectOptions().apply {
    isAutomaticReconnect = true
    connectionTimeout = 30
    isCleanSession = false
}

mqttClient.connect(options, null, connectListener)

The success callback should subscribe to the minimum topics required by the screen. MQTT over TLS with native TCP generally offers lower overhead on mobile networks, while WebSockets can be useful when the broker must share port 443 with other web traffic. Background execution should rely on Android lifecycle-aware components rather than an unrestricted service that remains active indefinitely.

Comparing MQTT Broker Deployment Options

Broker choice affects security, operating costs and the amount of infrastructure an organisation must maintain. A development broker can simplify tutorials, but its shared credentials and variable availability make it unsuitable for production equipment or customer data.

Deployment option Main benefits Costs and risks Best fit
Public development broker Fast setup and no server administration Limited reliability, shared credentials and unsuitable security Local prototypes and tutorials
Managed cloud broker Automatic scaling, monitoring and per-device authentication Recurring fees and potential vendor dependence Production device fleets
Self-hosted Mosquitto Full control over topics, backups and network placement Patching, monitoring and disaster recovery remain the operator’s responsibility Small deployments and controlled networks
Broker connected to a regional gateway Combines MQTT routing with LoRaWAN, Bluetooth or other field networks Adds gateway configuration and radio-network troubleshooting Farms, utilities and remote installations

Australian farms can use LoRaWAN sensors with a local gateway that converts messages into MQTT topics for cloud dashboards. MQTT does not replace the radio protocol; it provides a common northbound interface for Android clients. Choosing a managed broker with an Australian region can also reduce latency and help satisfy data-location expectations, while self-hosting offers greater control over traffic and retention.

Security and Australian IoT Requirements

Connections should use TLS, and every device should receive its own revocable credentials. Embedded shared passwords are vulnerable to extraction from an APK, so production systems should use short-lived tokens, broker-side authorisation rules or per-device certificates. Topic permissions must prevent a thermostat from subscribing to every building’s telemetry, and custom trust managers that accept invalid certificates should never be used.

The Privacy Act 1988 and Australian Privacy Principles apply when an app handles personal information. Names, precise home locations, occupancy patterns and identifiable device records should be collected only for a defined purpose, secured appropriately and removed when no longer required. The Australian Consumer Law also matters when an MQTT app accompanies a consumer product: compatibility, energy savings and monitoring claims must be accurate and clearly explained.

Weather and infrastructure interruptions make dependable alerting important. Heat spikes in Melbourne, storm outages around Brisbane and bushfire activity in regional New South Wales can affect both sensors and users. For user-visible warnings, Android’s notification channel guidance explains how to create channels with suitable priority and user controls. Notifications should provide useful context rather than exposing sensitive household details on a lock screen.

Reliable Testing and Field Deployment

Test the Android app under the network and lifecycle conditions it will encounter. MQTT’s automatic reconnection is helpful, but it does not guarantee that subscriptions, local state and offline messages will always remain consistent.

Build and broker checks

  • Exercise clean and persistent sessions, including reconnects after the broker restarts.
  • Move between Wi-Fi and mobile data while the app enters the background.
  • Publish duplicate, delayed, oversized and malformed messages to verify validation.
  • Test retained values, wildcard subscriptions and Last Will transitions.

Field deployment checks

  • Monitor connection counts, delivery latency, error codes, sensor battery levels and broker storage.
  • Buffer unsent readings locally and attach timestamps or sequence numbers.
  • Rotate credentials and revoke access for retired or lost devices.
  • Review topic permissions, payload schemas and privacy statements after broker updates.

A staged pilot exposes unreliable network paths and device differences before a wider rollout. By combining persistent sessions, validated payloads, revocable credentials and observable broker metrics, an Android MQTT application can remain useful across Australian homes, farms, retail systems and industrial environments.