目录
版本:Android Studio 2024.1.1
SDK:34
一、添加MQTT依赖库
在app->build.gradle 添加MQTT依赖库
// MQTT 客户端库
implementation 'org.eclipse.paho:org.eclipse.paho.android.service:1.1.1'
implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.5'
如下所示:
plugins {
alias(libs.plugins.android.application)
}
android {
namespace 'com.example.mytest'
compileSdk 34
defaultConfig {
applicationId "com.example.mytest"
minSdk 29
targetSdk 34
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
// MQTT 客户端库
implementation 'org.eclipse.paho:org.eclipse.paho.android.service:1.1.1'
implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.5'
implementation libs.appcompat
implementation libs.material
implementation libs.activity
implementation libs.constraintlayout
implementation libs.filament.android
testImplementation libs.junit
androidTestImplementation libs.ext.junit
androidTestImplementation libs.espresso.core
}
二、添加申请权限
在app->src->main->AndroidManifest.xml添加申请权限
<!-- 网络权限-->
<uses-permission android:name="android.permission.INTERNET" />
<!-- 网络状态权限-->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!-- 保持唤醒状态-->
<uses-permission android:name="android.permission.WAKE_LOCK" />
<!-- 开启MQTT服务-->
<service android:name="org.eclipse.paho.android.service.MqttService" />
如下所示:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<!-- 网络权限-->
<uses-permission android:name="android.permission.INTERNET" />
<!-- 网络状态权限-->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!-- 保持唤醒状态-->
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.MyTest"
tools:targetApi="31">
<activity
android:name=".utils.ToastUtil"
android:exported="false" />
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- 开启MQTT服务-->
<service android:name="org.eclipse.paho.android.service.MqttService" />
</application>
</manifest>
三、封装工具类
源码:
package com.example.mytest.internet;
import android.util.Log;
import android.util.Property;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import java.util.Properties;
import javax.net.SocketFactory;
public class MyMqttHelper {
private static final String TAG = "MQTT"; //日志
private static final String BROKER_URL = "tcp://192.168.1.38:1883"; // 测试用的MQTT服务器(tcp://固定,不用管)
private static final String USERNAME = "android"; //用户名
private static final String PASSWORD = "123"; //密码
private static final String SUBTOPIC = "test/subtopic"; // MQTT主题
private static final String PUBTOPIC = "test/pubtopic"; // MQTT主题
private static MyMqttHelper instance; //单例模式变量
private MqttClient client;
private MqttConnectOptions options;
private MyMqttHelper() {
try {
client = new MqttClient(BROKER_URL, MqttClient.generateClientId(), new MemoryPersistence());
//MQTT连接参数 初始化
options = new MqttConnectOptions();
options.setCleanSession(true); //是否在连接时清理会话
options.setUserName(USERNAME); //设置用户名
options.setPassword(PASSWORD.toCharArray()); //设置密码
//options.setConnectionTimeout(30); //设置连接超时时间(单位:秒)
//options.setKeepAliveInterval(30); //设置心跳包发送间隔(单位:秒)
//options.setMaxInflight(5); //设置最大同时传输的消息数
//options.setSocketFactory(socketFactory); //Socket
//options.setSSLHostnameVerifier(Properties); //SSL
//options.setWill(TOPIC, "WillMessage".getBytes(), 2, true); //设置遗嘱消息,设备意外断开连接,服务器发送消息到指定主题
Log.d(TAG, "MyMqttHelper: init");
} catch (MqttException e) {
e.printStackTrace();
Log.e(TAG, "MyMqttHelper: excption");
}
}
//单例模式
public static MyMqttHelper getInstance() {
if(instance == null){
synchronized (MyMqttHelper.class){
if(instance == null){
instance = new MyMqttHelper();
}
}
}
return instance;
}
public void connect() {
try {
client.connect(options);
client.setCallback(new MqttCallback() {
@Override
public void connectionLost(Throwable cause) {
// 连接丢失
}
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
// 接收到消息
String payload = new String(message.getPayload());
Log.d(TAG, "messageArrived: " + payload);
}
@Override
public void deliveryComplete(IMqttDeliveryToken token) {
// 消息发送完成
}
});
} catch (MqttException e) {
e.printStackTrace();
}
}
public void disconnect() {
try {
client.disconnect();
} catch (MqttException e) {
e.printStackTrace();
}
}
public void publishMessage(String message) {
try {
MqttMessage mqttMessage = new MqttMessage(message.getBytes());
mqttMessage.setQos(2);
client.publish(PUBTOPIC, mqttMessage);
} catch (MqttException e) {
e.printStackTrace();
}
}
public void subscribeTopic() {
try {
client.subscribe(SUBTOPIC);
} catch (MqttException e) {
e.printStackTrace();
}
}
public void unsubscribeTopic() {
try {
client.unsubscribe(SUBTOPIC);
} catch (MqttException e) {
e.printStackTrace();
}
}
}
四、使用MQTT工具类(直接调用)
1.连接到MQTT服务器
MyMqttHelper.getInstance().connect();
2.发布消息
MyMqttHelper.getInstance().publishMessage("Hello");
3.订阅主题
MyMqttHelper.getInstance().subscribeTopic();
4.取消订阅主题
MyMqttHelper.getInstance().unsubscribeTopic();
5.断开与MQTT服务器的连接
MyMqttHelper.getInstance().disconnect();