概述
实现步骤:
一、云平台端
1、首先在阿里云物联网平台创建产品和设备,获取设备三元组
{
"ProductKey": "a1QRE182gGH",
"DeviceName": "你的设备名称",
"DeviceSecret": "1d070861a16da0b783689b8361117f1a"
}
2、然后根据设备三元组,得到相关参数,如何得到,查看对应文档章节MQTT.fx
Broker Address:
a1QRE182gGH.iot-as-mqtt.cn-shanghai.aliyuncs.com
Broker Port:
1883
Client ID:
你的设备id|securemode=3,signmethod=hmacsha1|
User Name:
你的设备名称&a1QRE182gGH
Password:
A2FE7B0972CEA0800F3F49EE504F2F70C*******
3、先用MQTT.fx调试助手连接阿里云平台成功,说明我们配置的参数正确
二、Android端
1、项目根目录build.gradle中添加:
allprojects {
repositories {
maven{ url "https://repo.eclipse.org/content/repositories/paho-snapshots/"}
}
}
2、在build.gradle中添加依赖:
dependencies {
...
//mqtt
implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.1.0'
implementation 'org.eclipse.paho:org.eclipse.paho.android.service:1.1.1'
}
3、mainfests清单文件中添加权限:
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
4、mainfests中的application中添加应用:
<!-- Mqtt服务 -->
<service android:name="org.eclipse.paho.android.service.MqttService" />
5、为了方便管理,这里定义一个工具类MqttManager.java,相关MQTT的操作放在这里面
package com.example.mqtttest;
import android.content.Context;
import android.util.Log;
import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttMessage;
/**
* Mqtt工具
*/
public class MqttManager {
//MQTT相关配置
//服务器地址(协议+地址+端口号)
private final static String HOST = "tcp://a1QRE182gGH.iot-as-mqtt.cn-shanghai.aliyuncs.com:1883"; //修改改为你的host
private final static String CLIENTID = "YouDeviceName|securemode=3,signmethod=hmacsha1|"; //修改为你的clientId
private final static String USERNAME = "YouDeviceName&a1QRE182gGH"; //修改为你的用户名
private final static String PASSWORD = "A2FE7B0972CEA0800F3F49EE504F2F70C533E6B6******"; // 修改为你的密码
//服务质量,0最多一次,1最少一次,2只一次
private final static int QOS = 0;
private Context mContext;
private static MqttManager mqttManager;
private MqttAndroidClient mqttClient;
private MqttConnectOptions mqttConnectOptions;
/**
* 构造函数
*/
private MqttManager(Context context) {
this.mContext = context;
initMqtt();
}
/**
* 单例模式
*/
public static MqttManager getInstance(Context context) {
if (mqttManager == null) {
mqttManager = new MqttManager(context);
}
return mqttManager;
}
/**
* 初始化
*/
private void initMqtt() {
//创建Mqtt客户端
mqttClient = new MqttAndroidClient(mContext, HOST, CLIENTID);
mqttClient.setCallback(mqttCallback); //设置订阅消息的回调
mqttConnectOptions = new MqttConnectOptions();
mqttConnectOptions.setCleanSession(true); //设置是否清除缓存
mqttConnectOptions.setConnectionTimeout(30); //设置超时时间,单位:秒
mqttConnectOptions.setKeepAliveInterval(60); //设置心跳包发送间隔,单位:秒
mqttConnectOptions.setUserName(USERNAME); //设置用户名
mqttConnectOptions.setPassword(PASSWORD.toCharArray()); //设置密码
}
/**
* MQTT是否连接成功的监听
*/
private IMqttActionListener iMqttActionListener = new IMqttActionListener() {
@Override
public void onSuccess(IMqttToken asyncActionToken) {
Log.i("--->mqtt", "连接成功 ");
try {
//订阅主题,参数:主题、服务质量
//mqttClient.subscribe(SUB_TOPIC, QOS);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
exception.printStackTrace();
}
};
/**
* 订阅主题的回调
*/
private MqttCallback mqttCallback = new MqttCallback() {
@Override
public void connectionLost(Throwable cause) {
cause.printStackTrace();
}
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
Log.i("--->mqtt", "收到消息: " + new String(message.getPayload()) + "tToString:" + message.toString());
//收到其他客户端的消息后,响应给对方告知消息已到达或者消息有问题等
//response("message arrived:"+message);
}
@Override
public void deliveryComplete(IMqttDeliveryToken token) {
Log.i("--->mqtt", "deliveryComplete");
}
};
/**
* 建立mqtt连接,连接MQTT服务器
*/
public boolean connectServer() {
try {
if ((mqttClient != null) && (!mqttClient.isConnected())) {
mqttClient.connect(mqttConnectOptions, null, iMqttActionListener);
}
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
/**
* 发布消息
*/
// 订阅主题
public void subTopic(String topic, int qos) {
if (mqttClient != null && mqttClient.isConnected()) {
try {
mqttClient.subscribe(topic, qos);
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 发布消息
*/
public void pubTopic(String topic,String payLoad) {
try {
if (mqttClient != null && mqttClient.isConnected()) {
//参数分别为:主题、消息的字节数组、服务质量、是否在服务器保留断开连接后的最后一条消息
mqttClient.publish(topic,payLoad.getBytes(),QOS,false);
} else {
Log.i("--->mqtt","mqttAndroidClient is Null or is not connected");
}
} catch (Exception e) {
Log.i("--->mqtt","publish MqttException:" + e.getMessage());
e.printStackTrace();
}
}
/**
* 断开链接
*/
public void disconnect() {
try {
if (mqttClient != null) {
mqttClient.unregisterResources();
mqttClient.disconnect();
mqttClient = null;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
6、在MainActivity中编写代码
private MqttManager mqttManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mqttManager= MqttManager.getInstance(this);
}
public void connectServer(View view) {
mqttManager.connectServer();
}
7、运行点击button,再去云平台看连接成功
最后
以上就是坦率小蝴蝶为你收集整理的物联网阿里云——Android Mqtt协议连接阿里云的全部内容,希望文章能够帮你解决物联网阿里云——Android Mqtt协议连接阿里云所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复