Android Studio 2022 + MQTT连接阿里云

一、概述

本项目制作了一个手机端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
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值