1添加依赖
在项目中找到下图文件
打开文件
如下
plugins {alias(libs.plugins.android.application)
}android {namespace = "com.example.mqtt_04"compileSdk = 34defaultConfig {applicationId = "com.example.mqtt_04"minSdk = 27targetSdk = 34versionCode = 1versionName = "1.0"testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"}buildTypes {release {isMinifyEnabled = falseproguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")}}compileOptions {sourceCompatibility = JavaVersion.VERSION_1_8targetCompatibility = JavaVersion.VERSION_1_8}
}dependencies {implementation(libs.appcompat)implementation(libs.material)implementation(libs.activity)implementation(libs.constraintlayout)testImplementation(libs.junit)androidTestImplementation(libs.ext.junit)androidTestImplementation(libs.espresso.core)
}
在dependencies节点中添加如下语句
implementation("org.eclipse.paho","org.eclipse.paho.client.mqttv3","1.2.5")
此文件中上方会显示是否同步
点击同步
依赖会自动下载
2添加网路权限
找到如下文件
在文件中在
<application
节点的上方添加权限选中的是要添加的权限
<uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.WAKE_LOCK" /><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
权限添加完成
3创建MQTT类
在类中添加 连接 订阅 发布 和 关闭 方法
package com.example.mqtt_04;import android.os.Message;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.nio.charset.StandardCharsets;public class MQTT_xie_yi {private static MqttClient client;private static MqttConnectOptions options;//建立连接public static void Mqtt_init() throws MqttException {//创建客户端对象client=new MqttClient("tcp://(写入自己的IP):(写入IP的端口号)","app_MQTT_04",new MemoryPersistence());//创建连接options=new MqttConnectOptions();options.setCleanSession(true);//可以设置如用户名 密码 等等//将配置给客户端client.connect(options);}//订阅public static String SubClient() throws MqttException {final String[] a1 = {""};client.setCallback(new MqttCallback() {@Overridepublic void connectionLost(Throwable cause) {//连接断开是}@Overridepublic void messageArrived(String topic, MqttMessage message) throws Exception {//接收到信息a1[0] =new String(message.getPayload());}@Overridepublic void deliveryComplete(IMqttDeliveryToken token) {//接收信息完成后}});//开始订阅client.subscribe("wd");//返回数据return a1[0];}//发布public static void PubClient(String a2) throws MqttException {//创建消息对象MqttMessage mqttMessage=new MqttMessage(("信息为:"+a2).getBytes(StandardCharsets.UTF_8));//设置消息等级mqttMessage.setQos(0);//发布消息client.publish("wd",mqttMessage);}//关闭客户端//会将此线程关闭在没有重建一条线程去运行会退出页面public static void guan_bi() throws MqttException {//断开连接client.disconnect();//关闭客户端client.close();}
}
主函数中调用即可
要将IP改为自己的IP