添加MQTT依赖
implementation ‘org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.2’
implementation ‘org.eclipse.paho:org.eclipse.paho.android.service:1.1.1’
在Manifest清单文件中添加服务
<service android:name="org.eclipse.paho.android.service.MqttService" />
两种实现方法
MqttClient的实现方式
MQTT初始化连接线程,实现与服务器的连接、订阅、发布消息
private class ConnectTask extends AsyncTask<Void, String, Boolean> {
//MQTT连接线程,实现与服务器的连接、订阅、发布消息
/**
* 异步任务:AsyncTask<Params, Progress, Result>
* 1.Params:UI线程传过来的参数。
* 2.Progress:发布进度的类型。
* 3.Result:返回结果的类型。耗时操作doInBackground的返回结果传给执行之后的参数类型。
*
* 执行流程:
* 1.onPreExecute()
* 2.doInBackground()-->onProgressUpdate()
* 3.onPostExecute()
*/
@Override
protected void onPreExecute() //执行耗时操作之前处理UI线程事件
{
super.onPreExecute();
isConnecting = true;
connectionStatusTextView.setText("Connecting...");
}
@Override
protected Boolean doInBackground(Void... voids)
{
//在此方法执行耗时操作,耗时操作中收发MQTT服务器的数据
//MQTT服务器地址
String brokerUrl = "tcp://www.10086.com:1883";
//客户端ID,用于在MQTT服务器上
String clientId = MqttClient.generateClientId();
try {
mqttClient = new MqttClient(brokerUrl, clientId, new MemoryPersistence());
} catch (MqttException e) {
throw new RuntimeException(e);
}
MqttConnectOptions connectOptions = new MqttConnectOptions();
connectOptions.setCleanSession(true);
//mqtt服务器用户名和密码
connectOptions.setUserName("username");
connectOptions.setPassword("password".toCharArray());
connectOptions.setWill("断线消息主题","断线消息内容".getBytes(),1,true);
connectOptions.setConnectionTimeout(10);
connectOptions.setKeepAliveInterval(20);
try {
mqttClient.connect(connectOptions);
mqttClient.setCallback(new MqttCallback() {
@Override
public void connectionLost(Throwable throwable) {
Log.e(TAG, "连接丢失");//连接丢失的时候可以在这里进行重新连接
publishProgress("Connection lost, reconnecting...");
new ReconnectTask().execute();
}
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
Log.i(TAG, "收到消息:"+message.toString());
if (topic.equals("sensors/temperature")) {
// Update temperature reading
publishProgress("Temperature: " + message.toString());
} else if (topic.equals("sensors/humidity")) {
// Update humidity reading
publishProgress("Humidity: " + message.toString());
} else if (topic.equals("leds/led1/status")) {
// Update LED 1 status
if (message.toString().equals("on")) {
publishProgress("LED 1 is on");
ledStatusImageView.setText("LED 1 is on");
} else {
publishProgress("LED 1 is off");
ledStatusImageView.setText("LED 1 is off");
}
} else if (topic.equals("leds/led2/status")) {
// Update LED 2 status
if (message.toString().equals("on")) {
publishProgress("LED 2 is on");
ledStatusImageView.setText("LED 2 is on");
} else {
publishProgress("LED 2 is off");
ledStatusImageView.setText("LED 2 is off");
}
}
}
@Override
public void deliveryComplete(

本文详细介绍了在Android应用中使用MQTT协议的客户端和服务端实现,包括MqttClient的连接、订阅、发布消息以及MqttAndroidClientService的配置和处理连接丢失、重连和断开情况,同时涉及CleanSession和自动重连选项的设置。

1万+

被折叠的 条评论
为什么被折叠?



