实现步骤:
一、云平台端
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中添加:
1
2
3
4
5allprojects { repositories { maven{ url "https://repo.eclipse.org/content/repositories/paho-snapshots/"} } }
2、在build.gradle中添加依赖:
1
2
3
4
5
6dependencies { ... //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清单文件中添加权限:
1
2
3
4
5
6<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中添加应用:
1
2<!-- Mqtt服务 --> <service android:name="org.eclipse.paho.android.service.MqttService" />
5、为了方便管理,这里定义一个工具类MqttManager.java,相关MQTT的操作放在这里面
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173package 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中编写代码
1
2
3
4
5
6
7
8
9
10
11
12private 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内容请搜索靠谱客的其他文章。
发表评论 取消回复