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;
		}
	}
};
相关推荐
Yang-Never3 小时前
Kotlin协程 -> Job.join() 完整流程图与核心源码分析
android·开发语言·kotlin·android studio
一笑的小酒馆8 小时前
Android性能优化之截屏时黑屏卡顿问题
android
懒人村杂货铺11 小时前
Android BLE 扫描完整实战
android
TeleostNaCl13 小时前
如何安装 Google 通用的驱动以便使用 ADB 和 Fastboot 调试(Bootloader)设备
android·经验分享·adb·android studio·android-studio·android runtime
fatiaozhang952714 小时前
中国移动浪潮云电脑CD1000-系统全分区备份包-可瑞芯微工具刷机-可救砖
android·网络·电脑·电视盒子·刷机固件·机顶盒刷机
2501_9159184115 小时前
iOS 开发全流程实战 基于 uni-app 的 iOS 应用开发、打包、测试与上架流程详解
android·ios·小程序·https·uni-app·iphone·webview
lichong95115 小时前
【混合开发】vue+Android、iPhone、鸿蒙、win、macOS、Linux之dist打包发布在Android工程asserts里
android·vue.js·iphone
Android出海15 小时前
Android 15重磅升级:16KB内存页机制详解与适配指南
android·人工智能·新媒体运营·产品运营·内容运营
一只修仙的猿15 小时前
毕业三年后,我离职了
android·面试
编程乐学16 小时前
安卓非原创--基于Android Studio 实现的新闻App
android·ide·android studio·移动端开发·安卓大作业·新闻app