一、概述
本项目制作了一个手机端APP,一个遥控器,通过MQTT协议连接阿里云,实现对下位机的操控,并监控下位机的状态。使用Paho接入物联网平台,参考阿里云Paho-MQTT Android接入示例。鉴于阿里云示例项目使用的android studio版本较老,且恰逢android studio 2022.3.1版本发布,本项目就使用了最新的版本完成该项目。
二、开发步骤
1、工程创建
工程创建和之前的版本没有太大区别,这里就不详述了。
2、导入库文件
这里使用了两个库文件,一个是org.eclipse.paho.client.mqttv3-1.2.5.jar,另一个是org.eclipse.paho.android.service-1.1.1.jar。实际上,后面这个库可以不用的,这里用它的原因是mqtt库不支持自动重连,而后面这个库支持。导入方法有两种:一是如下图所示,直接下载文件包粘贴到app下的libs文件夹下,右键导入即可;另一种就是在app模块的build.gradle文件中implementation,效果是一样的。网络不好的情况还是建议使用第一种方法。
3、添加依赖
在工程的settings.gradle中添加Paho仓库地址。
4、添加support-v4对应的兼容包
5、开启网络权限,添加服务
6、代码编写
6.1布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#c0ffff"
tools:context=".MainActivity">
<Space
android:layout_width="match_parent"
android:layout_height="80dp"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="4">
<Space
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"/>
<TextView
android:layout_width="60dp"
android:layout_height="match_parent"
android:text="状态:"
android:textSize="30dp"
android:layout_weight="1"/>
<TextView
android:id="@+id/textView"
android:layout_width="60dp"
android:layout_height="match_parent"
android:background="#FFFFFF"
android:gravity="center"
android:text=" "
android:textSize="30dp"
android:layout_weight="1"/>
<Space
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"/>
</LinearLayout>
<Space
android:layout_width="match_parent"
android:layout_height="80dp"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:we