Android mqtt 客户端实现一般使用以下两个库:

implementation 'org.eclipse.paho:org.eclipse.paho.android.service:1.1.1'

implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.1.1'

一般Android 客户端的连接代码可以这样写:

import android.content.Context;

import android.util.Log;

import org.eclipse.paho.android.service.MqttAndroidClient;

import org.eclipse.paho.client.mqttv3.IMqttActionListener;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;

import org.eclipse.paho.client.mqttv3.IMqttToken;

import org.eclipse.paho.client.mqttv3.MqttCallback;

import org.eclipse.paho.client.mqttv3.MqttConnectOptions;

import org.eclipse.paho.client.mqttv3.MqttException;

import org.eclipse.paho.client.mqttv3.MqttMessage;

public class MqttClient {

private static MqttClient instance;

private Context context;

//单例模式

public static MqttClient getInstance(Context context) {

if (null == instance) {

synchronized (MqttClient.class) {

instance = new MqttClient(context);

}

}

return instance;

}

private MqttClient(Context context) {

this.context = context.getApplicationContext();

}

//声明一个MQTT客户端对象

private MqttAndroidClient mMqttClient;

private static final String TAG = "MqttClient";

//连接到服务器

private void connectMQTT() {

//连接时使用的clientId, 必须唯一, 一般加时间戳

String clientId = "xxxx" + System.currentTimeMillis();

mMqttClient = new MqttAndroidClient(context, "tcp://xxxxhost:xxxxport", clientId);

//连接参数

MqttConnectOptions options;

options = new MqttConnectOptions();

//设置自动重连

options.setAutomaticReconnect(true);

// 缓存,

options.setCleanSession(true);

// 设置超时时间,单位:秒

options.setConnectionTimeout(15);

// 心跳包发送间隔,单位:秒

options.setKeepAliveInterval(15);

// 用户名

options.setUserName("username");

// 密码

options.setPassword("password".toCharArray());

// 设置MQTT监听

mMqttClient.setCallback(new MqttCallback() {

@Override

public void connectionLost(Throwable cause) {

Log.d(TAG, "connectionLost: 连接断开");

}

@Override

public void messageArrived(String topic, MqttMessage message) throws Exception {

Log.d(TAG, "消息到达");

}

@Override

public void deliveryComplete(IMqttDeliveryToken token) {

}

});

try {

//进行连接

mMqttClient.connect(options, null, new IMqttActionListener() {

@Override

public void onSuccess(IMqttToken asyncActionToken) {

Log.d(TAG, "onSuccess: 连接成功");

try {

//连接成功后订阅主题

mMqttClient.subscribe("some topic", 2);

} catch (MqttException e) {

e.printStackTrace();

}

}

@Override

public void onFailure(IMqttToken asyncActionToken, Throwable exception) {

Log.d(TAG, "onFailure: 连接失败");

}

});

} catch (MqttException e) {

e.printStackTrace();

}

}

}

几个重要参数的介绍:

这里最重要的是对几个关键参数的理解。

options.setAutomaticReconnect(true);

先看官方的解释:

Sets whether the client will automatically attempt to reconnect to the server if the connection is lost.

If set to false, the client will not attempt to automatically reconnect to the server in the event that the connection is lost.

If set to true, in the event that the connection is lost, the client will attempt to reconnect to the server. It will initially wait 1 second before it attempts to reconnect, for every failed reconnect attempt, the delay will double until it is at 2 minutes at which point the delay will stay at 2 minutes.

设置为true表示支持自动重连。 这里的重连机制是:先1秒之后尝试重连,然后翻倍2秒后再尝试重连,最后一直稳定重连间隔时间为2分钟。

options.setCleanSession(true);

这个标志是标志客户端,服务端是否要保持持久化的一个标志。默认是true。这个标志理解起来并不容易

先看官方的解释:

Sets whether the client and server should remember state across restarts and reconnects.

If set to false both the client and server will maintain state across restarts of the client, the server and the connection. As state is maintained:

Message delivery will be reliable meeting the specified QOS even if the client, server or connection are restarted.

The server will treat a subscription as durable.

If set to true the client and server will not maintain state across restarts of the client, the server or the connection. This means

Message delivery to the specified QOS cannot be maintained if the client, server or connection are restarted

The server will treat a subscription as non-durable

设置客户端和服务端重启或重连后是否需要记住之前的状态。

当setCleanSession为true时,客户端掉线或服务端重启后,服务端和客户端会清掉之前的 session, 重连后客户端会有一个新的session。离线期间发来QoS=0,1,2的消息一律接收不到,且所有之前订阅的topic需要重新订阅。

当setCleanSession为false时, 客户端掉线或服务端重启后,服务端和客户端不会清除之前的session。重连后session将会恢复,客户端不用重新订阅主题。且离线期间发来QoS=0,1,2的消息仍然可以接收到。

这里有个需要注意的地方,即setCleanSession为true时,掉线后客户端设置了setAutomaticReconnect为true才会自动重连。为当setCleanSession为false时。不管setAutomaticReconnect为true或者false都会自动重连。

options.setKeepAliveInterval(15);

Sets the "keep alive" interval. This value, measured in seconds, defines the maximum time interval between messages sent or received. It enables the client to detect if the server is no longer available, without having to wait for the TCP/IP timeout. The client will ensure that at least one message travels across the network within each keep alive period. In the absence of a data-related message during the time period, the client sends a very small "ping" message, which the server will acknowledge. A value of 0 disables keepalive processing in the client.

这个字段是设置keepalive时间间隔的。

MQTT客户端(client)在没有收到或发布任何消息时仍然是保持连接的。服务端(the broker)需要跟踪客户端的连接状态。 所有需要发送心跳包来确定客户端是否是连接状态。心跳包发送的时间间隔就是keepalive设置的。

服务端都会维持一个timer。当这个timer记录的时间超过1.5倍keepalive值时,服务端会将这个客户端标记为断开连接,并发送Last Will and Testament (LWT)遗言广播。

以下情况下会重置这个timer:

每次客户端发送或接收一个消息, 服务端会重置这个timer。

一个客户端可以在任何时间发送一个PINGREQ的消息到服务器,服务器如果收到这个消息后,会回一个PINGRESP消息,然后服务端会重置这个timer。

paho client在一个 keepalive时间间隔内没有向 Broker 发送任何数据包,比如 PUBLISH 和 SUBSCRIBE 的时候,它会向 Broker 发送 PINGREQ数据包,告诉服务器自己仍然是连接的。

遇到的问题及解决方法

1.断线重连后收不到消息。

一般是由于我们设置了setCleanSession=true时,且setAutomaticReconnect(true),这样mqtt客户端断线后会启动自动重连机制。但是由于CleanSession=true会启动一个新的session,这样需要重新订阅topic。如果我们没有重新订阅topic,就会导致断线重连后收不到消息。

此时

我们需要将Callback替换成MqttCallbackExtended,并在重写方法connectComplete重新订阅即可。

public void connectComplete(boolean reconnect, String serverURI){

client.subscribe(topics,Qos);//具体订阅代码

}```

android paho框架,Android Mqtt 客户端paho使用心得相关推荐

  1. android版本更新框架、新闻客户端、音乐播放器、自定义View、Github客户端、指南针等源码...

    Android精选源码 XUpdate 一个轻量级.高可用性的Android版本更新框架 Android一个可定制的圆形进度条 Android自定义View分享 打钩动画源码 android音乐文件播 ...

  2. android集成测试框架,Android单元测试框架选择

    Android单元测试介绍 处于高速迭代开发中的Android项目往往需要除黑盒测试外更加可靠的质量保障,这正是单元测试的用武之地.单元测试周期性对项目进行函数级别的测试,在良好的覆盖率下,能够持续维 ...

  3. android paho框架,Android 开发笔记 04 篇:Mqtt 框架 - Paho Java

    官方文档:Eclipse Paho Java Client API:Package org.eclipse.paho.client.mqttv3 Paho 基础知识 Paho Java 客户端是用 J ...

  4. MQTT客户端paho.mqtt.XXX

    1. MQTT客户端C代码库 C语言库:https://github.com/eclipse/paho.mqtt.c 1.1 C源码下载构建 # centos7 OS 方法一 $ git clone ...

  5. eclipse paho java_如何使用Eclipse Paho在Java MQTT客户端上接收时发布消息

    我正在尝试使用 Eclipse Paho在Java中的MQTT客户端上实现某些功能.目标是订阅主题,并且当收到消息时,客户端发送关于另一主题的另一消息. 这看起来很容易,但我有一个奇怪的问题,我无法解 ...

  6. android壁纸框架,Android仿百度壁纸客户端之搭建主框架(一)

    这是个不错的教程,自己学完了之后就拿出来分享了,本来想一个帖子写完,但是发现这样对自己写博客的效率有点出入,为了让大家看的舒服点,所以分开来写,我们先开看下百度壁纸的客户端是什么样子的 我们先来写个主 ...

  7. MQTT客户端 Paho Java 使用

    文章目录 01.maven 依赖 02.代码 1-publisher 发布者 2-订阅者 subscriber 01.maven 依赖 <dependency><groupId> ...

  8. android 电子书框架,[Android] Pdf开发框架使用

    最近项目中有个需求,在App中需要打开pdf文件格式.由于Android平台是没有直接去阅读pdf的方案,只能去调用外部程序去打开pdf文件.这里只好去求助github的帮助,下面介绍一个有关于pdf ...

  9. 精美的android ui框架,Android酷炫实用的开源框架(UI框架)

    前言 忙碌的工作终于可以停息一段时间了,最近突然有一个想法,就是自己写一个app,所以找了一些合适开源控件,这样更加省时,再此分享给大家,希望能对大家有帮助. 1.Side-Menu.Android ...

最新文章

  1. Android mediaRecorder框架简述(一)
  2. Mac OS 查看系统版本信息/硬件信息的命令
  3. [css] 怎样去除图片自带的边距?
  4. win7和Ubuntu16.04之间相互远程控制
  5. 【clickhouse】clickhouse 大表删除 Size 256G is greater than max_[table/partition]_size_to_drop 50GB
  6. iframe透明问题
  7. python识字_python代码实现截图识字
  8. 机器学习的transformer
  9. Xtrabackup 数据备份工具使用方法
  10. 阿里云监控列表和内存使用率数据展示为N/A,怎么办?
  11. Alpha版本冲刺(七)
  12. 数据可视化 | Tableau从入门到高手 入门联接关系数据预处理
  13. 各种格式的文档互相转换(MOBI_to_PDF)
  14. Oracle 11.2.0.3 ORA-12012 ORA-29280 ORA-06512 错误 解决方法
  15. 对未来编程学习的规划
  16. Web渗透信息收集之域名、端口、服务、指纹、旁站、CDN和敏感信息
  17. Excel中如何合并多个工作簿或者合并多个表格(利用方方格子)
  18. 计算机组成原理乘法运算说明过程,计算机组成原理第二章 第8讲 定点乘法运算...
  19. 用excel计算分布表
  20. HttpMessageNotWritableException: No converter found for return value of type,可能出现的原因及解决方法

热门文章

  1. 测试如何一眼看穿代码
  2. css文字渐变色设置
  3. 关于Numpy处理图像和提取图像色位:照片加滤镜的Python方案
  4. 数字功放-韩国Wellang原装WA15-6819B
  5. 关于英文商标或者标识的命名方式
  6. 2008,骗子仍在行动
  7. 中国古代历史知识点(一)
  8. 秒拍移动视频峰会|一下科技韩坤:移动视频不是颠覆者而是迭代者
  9. ajax异步加载延时问题,关于js延迟加载(异步操作)的方式
  10. Centos安装Redis