Android 发送MQTT消息

现在物联网很多都是使用的MQTT消息,在手机和设备之间通过MQTT协议通信,Android发送MQTT消息就会用得比较多。

步骤1:添加依赖库

你需要在你的build.gradle文件中添加MQTT客户端库。一个常用的库是Eclipse Paho,你可以这样添加依赖:

复制代码
dependencies {
    implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.5'
}

步骤2:设置网络权限

在AndroidManifest.xml中增加:

XML 复制代码
<!--网络权限-->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

步骤3:前台代码(layout.xml)

在视图文件中增加按钮。

XML 复制代码
<LinearLayout
	android:layout_width="match_parent"
	android:layout_height="wrap_content"
	android:gravity="center_horizontal"
	android:orientation="horizontal">
	<Button
		android:id="@+id/btnTest"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:layout_marginTop="10dp"
		android:text="测试"
		android:textAlignment="center" />
</LinearLayout>

步骤4:后台代码

java 复制代码
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;

... ...

btnTest.setOnClickListener(view -> {

	new Thread(() -> {
		String context = "tcp://broker.emqx.io:1883";
		String clientId = "mqttx_20240804-android";
		String username = "username";
		String password = "password";
		String topic = "mqttx_20240804";
		try {
			MqttClient client = new MqttClient(context, clientId, new MemoryPersistence());
			MqttConnectOptions options = new MqttConnectOptions();
			options.setCleanSession(true);
			options.setUserName(username);
			options.setPassword(password.toCharArray());
			client.connect(options);

			String action =  "hello"; 
			MqttMessage message = new MqttMessage(action.getBytes());
			message.setQos(0);
			client.publish(topic, message);

			Message handlerMsg = new Message();
			handlerMsg.what = 1;
			handlerMsg.obj = action;
			handler.sendMessage(handlerMsg);

		} catch (MqttException e) {
			Message message = new Message();
			message.what = 2;
			message.obj = e.getMessage();
			handler.sendMessage(message);
		}
	}).start();

});
java 复制代码
public Handler handler = new Handler() {
	@SuppressLint("HandlerLeak")
	@Override
	public void handleMessage(Message msg) {
		String text = msg.obj.toString(); 
		switch (msg.what) {
			case 1:
				Toast.makeText(ConfigActivity.this, "发送成功", Toast.LENGTH_SHORT).show();
				break;
			case 2:
				Toast.makeText(ConfigActivity.this, "抱歉,发送异常:" + text, Toast.LENGTH_SHORT).show();
				break;
		}
	}
};
相关推荐
执念WRD1 小时前
熊海CMS v1.0代码审计实战
android·nginx·安全·web安全·网络安全·系统安全
jllllyuz1 小时前
基于ThinkPHP实现动态ZIP压缩包的生成
android
百***92024 小时前
【MySQL】MySQL库的操作
android·数据库·mysql
2501_916008896 小时前
没有源码如何加密 IPA 实战流程与多工具组合落地指南
android·ios·小程序·https·uni-app·iphone·webview
2501_940094026 小时前
PS1模拟器 DuckStation更新最新版整合 下载即玩 附PS1Bios/游戏/金手指 安卓版+电脑版
android·游戏·电脑
橙武低代码8 小时前
业务流低代码平台:从理念到实战
android·低代码·ai编程
空白格979 小时前
三方框架必学系列#Retrofit
android
安卓程序猿9 小时前
kotlin build.gradle.kts下修改APK的输出名称
android·kotlin·gradle
wuwu_q9 小时前
通俗易懂 + Android 开发实战的方式,详细讲讲 Kotlin 中的 StateFlow
android·开发语言·kotlin
峰哥的Android进阶之路9 小时前
Kotlin面试题总结
android·开发语言·kotlin