preface

MQTT has been used in the recent project to receive some data pushed from the back end. This article will introduce how to integrate the use of The Android end and will not elaborate on MQTT.

Since it is difficult to verify that we have written the correct code without receiving the data in practice, I will briefly introduce how to configure an MQTT server and use tools to send data to the server so that the mobile phone can receive the data. Look at it without saying anything.

1. Configure the MQTT server

1.1 download EMQX

Download address

1.2 start EMQX

Run the CMD command in the bin directory after decompression and enter emqx. CMD start to start.

If you encounter the Could’t Load Module at startup… , that is because your path contains Chinese name, so you can not start the folder in pure English directory.

Enter http://127.0.0.1:18083 in the browser to open the web management page. The user name is admin and the password is public

Change the language to Chinese as shown in the figure

1.3 Interface Description

The Clients TAB on the left shows the currently connected ClientsYou can see the Topics currently subscribed to under the Topics TAB on the left

1.4 Personal Understanding

So once you get to this server and you’re configured, you might say, well, this is the server, how does my phone client receive messages, where does the server send messages from? The EMQX service is actually a messaging middleware service, sort of like forwarding. A client sends a message and specifies the topic, and the message is sent to the server, so all the clients connected to the server and subscribed to the topic can receive the message, so our mobile client wants to receive the message, there needs to be a side to send the message to the EMQX server.

2. MQTT client software Paho

2.1 Downloading the MQTT client software

Download address

Download the selected file, and then unzip it to get paho.exe, which is the client software we need.

2.2 Use of MQTT client

2.2.1 Connecting to the Server

Click as shown in the figure, 1. Add a connection, 2. Fill in the server address and customer idaddressAfter clicking connect, you can see that the connection status changes to connected, which means that our client has been connected to EMQX.

2.2.2 Sending Messages

Fill in the subject name in 1, the message in 2, and click Publish in 3. Then you can see that in 4, it says published, which means we have sent it to the server.

2.2.3 Subscribing to topics

Subscribe to the topic we just sent the message to

Click on 1 to add a subscription, click on 2 to enter the topic we want to subscribe to, here we set it to the topic we just posted the message to, then click on 3 to subscribe, you can see that the history shows the subscription.

Next we send the topic message again to observe the history

As you can see, when we publish, we receive messages for the topic because we subscribed to the topic.

Now that the MQTT server is configured and the MQTT client software is available for testing, let’s see how our Android side subscribs and receives messages.

3. Integrated use of Andoird terminal

3.1 Adding Dependencies and Permissions

//MQTT
implementation 'org. Eclipse. Paho: org. Eclipse paho. Client. Mqttv3:1.1.0'
implementation 'org. Eclipse. Paho: org. Eclipse paho. Android. Service: 1.1.1'
implementation 'androidx. Localbroadcastmanager: localbroadcastmanager: 1.0.0'
Copy the code

AndroidManifest file configuration

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.myfittinglife.mqttdemo"> <! -- necessary three permissions --> <uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <application ... >... <! --> < Service android:name="org.eclipse.paho.android.service.MqttService"/>
</application>
Copy the code

3.2 the use of

3.2.1 Creating an MqttAndroidClient object

var mClient: MqttAndroidClient? = null

private fun createClient(a) {

    // create an interface callback
    // All of the following callbacks are in the main thread (if MqttClient is used, all of them are outside the main thread)
    val mqttCallback: MqttCallbackExtended = object : MqttCallbackExtended {
        override fun connectComplete(reconnect: Boolean, serverURI: String) {
            // The connection succeeded
            Log.i(TAG, "connectComplete: ")
            showToast("Connection successful")}override fun connectionLost(cause: Throwable) {
            // Disconnect the connection
            Log.i(TAG, "connectionLost: ")
            showToast("Disconnect")}@Throws(Exception::class)
        override fun messageArrived(topic: String, message: MqttMessage) {
            // Get the message
            var msg = message.payload
            var str = String(msg)
            Log.i(TAG, "messageArrived: $str")
            showToast("The message received is:$str")}override fun deliveryComplete(token: IMqttDeliveryToken) {
            // Callback after successful message sending
            Log.i(TAG, "deliveryComplete: ")
            showToast("Sent successfully")}}// create a Client object
    try {
        mClient = MqttAndroidClient(this."TCP: / / 192.168.14.57:1883"."Client name, whatever you want.") mClient? .setCallback(mqttCallback)// Set the callback function
    } catch (e: MqttException) {
        Log.e(TAG, "createClient: ", e)
    }
}
Copy the code

3.2.2 Setting MQTT Connection Configuration Information

val mOptions = MqttConnectOptions()
mOptions.isAutomaticReconnect = false // Whether to automatically connect after disconnecting
mOptions.isCleanSession = true // Whether to clear client connection records. If true, the broker will automatically clear the client connection information after the disconnect
mOptions.connectionTimeout = 60 // Set the timeout period, in seconds
// moptions. userName = "Admin" // set the userName. It's different from the Client ID. A user name can be regarded as a permission level
// moptions. setPassword("Admin") // Sets the login password
mOptions.keepAliveInterval = 60 // Heartbeat time, in seconds. That is, how often to check whether the Client is online
mOptions.maxInflight = 10 // Allow multiple messages to be sent simultaneously (without receiving broker confirmation)
mOptions.mqttVersion = MqttConnectOptions.MQTT_VERSION_3_1_1 // Select the MQTT version
Copy the code

3.2.3 Establishing a Connection

try{ mClient? .connect(mOptions,this.object : IMqttActionListener {
        override fun onSuccess(asyncActionToken: IMqttToken?). {
            Log.i(TAG, "OnSuccess: connection successful")}override fun onFailure(asyncActionToken: IMqttToken? , exception:Throwable?). {
            Log.i(TAG, "onFailure: "+ exception? .message) } }) }catch (e: MqttException) {
    Log.e(TAG, "onCreate: ", e)
}
Copy the code

3.2.4 Subscribing to topics

// Set the topic to listen to
try{ mClient? .subscribe("topicName".0)}catch (e: MqttException) {
    Log.e(TAG, "onCreate: ", e)
}
Copy the code

3.2.5 Sending Messages

try {
    var str = "Message to send"
    varmsg = MqttMessage() msg.payload =str.toByteArray() mClient? .publish(Const.Subscribe.mTopic,msg) }catch (e: MqttException) {
    Log.e(TAG, "onCreate: ",e )
}
Copy the code

3.3 Final Effect

After our Paho MQTT Utility sends the message, our mobile phone can receive the message because it is subscribed to the topic.

4. Precautions

  • Don’t forget to add service to the manifest, otherwise mClient will be reported empty when connect().

    <service android:name="org.eclipse.paho.android.service.MqttService"/>
    Copy the code
  • Don’t forget to add localbroadcastmanager rely on, or you will quote Failed resolution of: Landroidx/localbroadcastmanager/content/localbroadcastmanager errors.

    implementation 'androidx. Localbroadcastmanager: localbroadcastmanager: 1.0.0'
    Copy the code
  • When starting the EMQX service, ensure that the file directory is in a pure English directory, which cannot contain Chinese characters. Otherwise, the could’t Load Module error will occur.

5. To summarize

Follow the above steps to complete the most basic functions, the above is just a simple use, in fact, you can set the user login name and password, set the quality of service, reconnect operations, etc. For more information about MQTT, see the article MQTT.

Github address of the project

If this article has helped you, please don’t forget the triple link, and if there are inappropriate places, please mention them. See you in the next article.

6. Refer to the article

Online API documentation

Free MQTT test server, measured found that can not be used

Paho website

Ali uses documents