MQTT protocol for message sending and receiving in Android

Keywords: Android Eclipse Session github

MQTT protocol for message sending and receiving in Android

Preface
MQTT (Message Queuing Telemetry Transport), a message protocol based on the publish/subscribe paradigm, is an extremely simple and lightweight message protocol designed for limited devices and networks with low bandwidth, high latency or unreliability.Today we will focus on the use of MQTT protocol for sending and receiving messages in Android. For the basics of MQTT protocol, please refer to the MQTT protocol described earlier.

Effect
Take a look at the simple effects before using, MQTT-related connections, subscriptions, sending and receiving:

Use process
Dependent Add
implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.0'
implementation 'org.eclipse.paho:org.eclipse.paho.android.service:1.1.1'
In practice, it is found that if we only use the first dependency, we can also achieve the message sending and receiving functions we need. The MqttClient class implements MQTT-related connection, subscription, sending and receiving functions. The second dependency is based on MqttClient encapsulating MqttAndroidClient for Android clients, which implements Android-related broadcasting and service phases.Off content.

If you are using an Androidx development environment, you also need to add the following dependencies, otherwise the local broadcast service will not be found in the MqttAndroidClient service and will not be able to run.

implementation 'androidx.legacy:legacy-support-v4:1.0.0'
Permission Add





Service Add

Here we focus on the MQTT protocol message sending and receiving implemented by the MqttClient class. The further encapsulated MqttAndroidClient is similar to its use process. To see its specific use, skip the corresponding Demo link for details.

Initialize the MQTT client content, which is implemented by the HiveMQ public proxy chosen by the broker proxy server:
public void initClient() {

try {
    MemoryPersistence persistence = new MemoryPersistence();
    // Set unique client ID
    clientId = clientId + System.currentTimeMillis();
    //Set up a Topic collection for subscribers'subscriptions, follow MQTT subscription rules, and can be a multilevel Topic collection
    final String topicFilter = topic;
    //Quality of Service, corresponding to topicFilter
    final int qos = 0;
    //Create Client
    sampleClient = new MqttClient(broker, clientId, persistence);
    //Configure Callback Functions
    sampleClient.setCallback(new MqttCallbackExtended() {
        @Override
        public void connectComplete(boolean reconnect, String serverUri) {
            setTextInfo("connectComplete: " + serverUri);
            try {
                //Successful connection requires all client subscription relationships to be uploaded
                sampleClient.subscribe(topicFilter, qos);
            } catch (MqttException e) {
                setTextInfo("subscribeException: " + e.getMessage());
            }
        }

        @Override
        public void connectionLost(Throwable cause) {
            setTextInfo("connectionLostException: " + cause.getMessage());
        }

        @Override
        public void messageArrived(String topic, MqttMessage message) {
            setTextInfo("messageArrived:" + new String(message.getPayload()));
        }

        @Override
        public void deliveryComplete(IMqttDeliveryToken token) {
            setTextInfo("deliveryComplete");
        }
    });
    //Create connection selection
    MqttConnectOptions connOpts = createConnectOptions(userName, passWord);
    setTextInfo("Connecting to broker: " + broker);
    //Create a service connection
    sampleClient.connect(connOpts);
} catch (MqttException me) {
    setTextInfo("initException: " + me.getMessage());
}

}
To create a connection, choose the following to set a user name and password:
private MqttConnectOptions createConnectOptions(String userName, String passWord) {

MqttConnectOptions connOpts = new MqttConnectOptions();
connOpts.setCleanSession(true);
connOpts.setUserName(userName);
connOpts.setPassword(passWord.toCharArray());
connOpts.setAutomaticReconnect(true);
// Set connection timeout in seconds, default 30
connOpts.setConnectionTimeout(30);
// Sets the session heartbeat time in seconds, default 20
connOpts.setKeepAliveInterval(20);
return connOpts;

}
Message Publishing:
public void publishMsg() {

String content = mEtMessage.getText().toString().trim();
if (TextUtils.isEmpty(content)) {
    content = "Hello MQTT ";
}
//Here the message body needs to pass in a byte array
MqttMessage message = new MqttMessage(content.getBytes());
//Set Quality Level
message.setQos(0);
try {
    if (sampleClient != null && sampleClient.isConnected()) {
        /*
         * Messages are sent to a topic Topic that can be received by all devices subscribing to it.
         * Following the MQTT publishing subscription specification, Topic can also be a multilevel Topic.Send to Level 1 Topic is set here.
         */
        sampleClient.publish(topic, message);
        setTextInfo("publishMsg: " + message);
    }
} catch (MqttException e) {
    setTextInfo(" publishException: " + e.getMessage());
}

}
Disconnect:
public void disconnect() {

try {
    sampleClient.disconnect();
} catch (MqttException e) {
    setMqttMessage("disconnectException: " + e.getMessage());
}

}
This is where the MQTT protocol enables messaging in Android. The content has been uploaded to the Github Development Record. Please Click to see and start. I will continue to add other useful knowledge and examples to the project.

Original Address https://www.cnblogs.com/jqnl/p/12660824.html

Posted by rivasivan on Wed, 08 Apr 2020 21:36:54 -0700