Android Paho客户端 - 如何在启用网络后启用离线缓冲和发送消息?

时间:2016-09-30 00:05:40

标签: java android mqtt paho

我使用的是Android Paho客户端库v1.1.0,QoS 2。 我在MQTT上的pub / sub代码:

mClient = new MqttAndroidClient(this, uri, clientId, new   MqttDefaultFilePersistence());
MqttConnectOptions conOpt = new MqttConnectOptions();

conOpt.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1);
conOpt.setCleanSession(true);
conOpt.setAutomaticReconnect(true);

mClient.setTraceEnabled(true);

mClient.setCallback(this);
mClient.setTraceCallback(this);

IMqttToken connectToken = mClient.connect(conOpt, null, this);

离线缓冲选项:

@Override
public void onSuccess(IMqttToken iMqttToken) {
    this.disconnectedBufferOptions = new DisconnectedBufferOptions();
    this.disconnectedBufferOptions.setBufferEnabled(true);

    mClient.setBufferOpts(disconnectedBufferOptions);

    subscribe(topic);
}

如果网络可用,则发布到主题的消息,但是如果它已禁用并再次启用脱机消息而不是发送。 如何正确启用离线缓冲选项并发送离线消息? 附加信息:禁用网络并发布message = 0后的mClient.getBufferedMessageCount()

1 个答案:

答案 0 :(得分:1)

使用conOpt.setAutomaticReconnect(true)以及连接令牌的onSuccess中的以下代码片段为我解决了这个问题。

DisconnectedBufferOptions disconnectedBufferOptions = new DisconnectedBufferOptions();

disconnectedBufferOptions.setBufferEnabled(true);
disconnectedBufferOptions.setBufferSize(100);
disconnectedBufferOptions.setPersistBuffer(false);
disconnectedBufferOptions.setDeleteOldestMessages(false);

mClient.setBufferOpts(disconnectedBufferOptions);