Communicate using custom MQTT topics

更新时间:
复制 MD 格式

Android Link SDK provides interfaces to publish, subscribe to, and unsubscribe from messages on Alibaba Cloud IoT Platform using custom MQTT topics.

The demo includes a complete code example in MqttActivity.java.

Publish messages

The MqttPublishRequest class provides the publish API.

  • Do not return an acknowledgement

    Use this mode when the device does not need a response from IoT Platform — either the platform does not reply, or the device does not process the reply.

    // Publish the message
    MqttPublishRequest request = new MqttPublishRequest();
    // Specify whether to require an acknowledgement.
    request.isRPC = false;
    // Set the topic. The device sends messages to IoT Platform over this topic. The following topic is an example. Replace it with the topic of your device.
    request.topic = "/a18wP******/LightSwitch/user/update";
    // Set the QoS level.
    request.qos = 0;
    String data = "hello world"; //TODO:data Set the data to publish.
    request.payloadObj = data;
    LinkKit.getInstance().publish(request, new IConnectSendListener() {
        @Override
        public void onResponse(ARequest aRequest, AResponse aResponse) {
            // The message is successfully submitted to the send buffer of the operating system.
            // The message may fail to arrive at the cloud due to network fluctuations or other issues.
            // If the mobile originated message has a corresponding mobile terminated reply, use the reply message to confirm that the mobile originated message has arrived.
        }
        @Override
        public void onFailure(ARequest aRequest, AError aError) {
            // The message failed to be published.
        }
    });                       

    Parameter

    Example

    Description

    isRPC

    false

    Whether this is an RPC request. If true, the response returns only after a message arrives from the replyTopic.

    Default: false (no acknowledgement required).

    topic

    /a18wP******/LightSwitch/user/update

    A topic the device has publish permission for.

    qos

    0

    QoS level of the MQTT request. Default: 0.

    payloadObj

    {"id":"160865432","method":"thing.event.property.post","params":{"LightSwitch":1},"version":"1.0"}

    The message payload. Accepts any format. For JSON strings, the id field must be unique per request — use auto-increment (for example, 160865432, then 160865433).

  • Return an acknowledgement

    • The device forwards a message to your server, which sends a reply back to the device.

    • The topic uses the Alink protocol, which requires a server reply.

    // Publish the message
    MqttPublishRequest request = new MqttPublishRequest();
    // Specify whether to require an acknowledgement. Set this to true if you expect a mobile terminated reply from IoT Platform.
    request.isRPC = true;
    // Set the QoS level.
    request.qos = 0;
    // Set the topic. The device sends messages to IoT Platform over this topic. The following topic is an example. Replace it with the topic of your device.
    request.topic = "/a18wP******/LightSwitch/user/update";
    // Set the topic for replies from IoT Platform. If you do not set this, the default reply topic is topic + "_reply".
    request.replyTopic = "/a18wP******/LightSwitch/user/update_reply";
    String data = "hello world"; //TODO:data Set the data to send.
    request.payloadObj = data;
    // The BaseTemplateActivity in the demo provides a reference class for message responses. The mobile terminated message is provided to the user in onResponse.
    LinkKit.getInstance().publish(request, new IConnectSendListener() {
        @Override
        public void onResponse(ARequest aRequest, AResponse aResponse) {
            // The message is published.
        }
        @Override
        public void onFailure(ARequest aRequest, AError aError) {
            // The message failed to be published.
        }  
    });                    

    Parameter

    Example

    Description

    isRPC

    true

    Whether this is an RPC request. If true, the response returns only after a message arrives from the replyTopic.

    Set to true when you expect a reply from IoT Platform.

    qos

    0

    QoS level of the MQTT request. Default: 0.

    topic

    /a18wP******/LightSwitch/user/update

    A topic the device has publish permission for.

    replyTopic

    /a18wP******/LightSwitch/user/update_reply

    Reply topic from IoT Platform. Defaults to the publish topic + "_reply".

    payloadObj

    {"id":"160865432","method":"thing.event.property.post","params":{"LightSwitch":1},"version":"1.0"}

    The message payload. Must be in JSON string format. The id field must be unique per request — use auto-increment (for example, 160865432, then 160865433).

Note

By default, onResponse and onFailure callbacks run on the UI thread. From lp-iot-linkkit 1.7.3+, set PersistentConnect.mNotifySendResultOnMainThread = false; to run callbacks on a non-UI thread. If the UI thread is busy, set this to false.

Subscribe to messages

Subscribe to a topic to receive messages forwarded by IoT Platform. IoT Platform saves the subscription relationship and forwards messages published to the topic. The MqttSubscribeRequest class provides the subscription API.

After subscribing, incoming messages are delivered via the IConnectNotifyListener object documented in the Connection status and mobile terminated message listener section of Authentication and connection.

Example code:

// Subscribe
MqttSubscribeRequest subscribeRequest = new MqttSubscribeRequest();
// Replace subTopic with the topic to which you want to subscribe.
subscribeRequest.topic = subTopic;
subscribeRequest.isSubscribe = true;
subscribeRequest.qos = 0; // Supports 0 or 1.
LinkKit.getInstance().subscribe(subscribeRequest, new IConnectSubscribeListener() {
    @Override
    public void onSuccess() {
        // The subscription is successful.
    }
    @Override
    public void onFailure(AError aError) {
        // The subscription failed.
    }
});                      

Unsubscribe from topics you no longer need — otherwise the subscription persists and messages keep arriving. See Unsubscribe below.

Unsubscribe

// Unsubscribe
MqttSubscribeRequest unsubRequest = new MqttSubscribeRequest();
// Replace unSubTopic with the topic from which you want to unsubscribe.
unsubRequest.topic = unSubTopic;
unsubRequest.isSubscribe = false;
LinkKit.getInstance().unsubscribe(unsubRequest, new IConnectUnscribeListener() {
    @Override
    public void onSuccess() {
        // The unsubscription is successful.
    }
    @Override
    public void onFailure(AError aError) {
        // The unsubscription failed.
    }
});