赞
踩
- implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.5'
- implementation 'org.eclipse.paho:org.eclipse.paho.android.service:1.1.1'
- <uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" tools:ignore="ProtectedPermissions" />
- <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" />
<service android:name="org.eclipse.paho.android.service.MqttService"/>
- android.useAndroidX=true
- android.enableJetifier=true
- private void connectToMQTT() {
- String serverUri = "tcp://183.230.40.39:6002";
- String clientId = "设备ID";
- String username = "产品ID";
- String password = "鉴权信息";
-
- mqttClient = new MqttAndroidClient(this, serverUri, clientId);
-
- MqttConnectOptions options = new MqttConnectOptions();
- options.setUserName(username);
- options.setPassword(password.toCharArray());
-
- try {
- mqttClient.connect(options, null, new IMqttActionListener() {
- @Override
- public void onSuccess(IMqttToken asyncActionToken) {
- // 连接成功(订阅主题)
- subscribeToTopic();
- }
-
- @Override
- public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
- // 连接失败
- exception.printStackTrace();
- }
- });
- } catch (MqttException e) {
- e.printStackTrace();
- }
- }
- private void subscribeToTopic() {
- String topic = "data/#";
- int qos = 1;
-
- try {
- mqttClient.subscribe(topic, qos, null, new IMqttActionListener() {
- @Override
- public void onSuccess(IMqttToken asyncActionToken) {
- // 订阅成功
- }
-
- @Override
- public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
- // 订阅失败
- exception.printStackTrace();
- }
- });
-
- mqttClient.setCallback(new MqttCallback() {
- @Override
- public void connectionLost(Throwable cause) {
- // 处理连接丢失的情况
- }
-
- @Override
- public void messageArrived(String topic, MqttMessage message) throws Exception {
- // 处理收到的消息
- String data = new String(message.getPayload());
- if(data.indexOf("temp")!=-1)
- {
-
- }
- }
-
- @Override
- public void deliveryComplete(IMqttDeliveryToken token) {
- // 处理消息发送完成的情况
- }
- });
- } catch (MqttException e) {
- e.printStackTrace();
- }
- }
- private void publishDataToMQTT() {
- String topic = "cmd/water";
- String payload = "flag:"+count;
- int qos = 1;
-
- try {
- MqttMessage message = new MqttMessage(payload.getBytes());
- message.setQos(qos);
-
- mqttClient.publish(topic, message);
- } catch (MqttException e) {
- e.printStackTrace();
- }
- }
- private void disconnectFromMQTT() {
- try {
- mqttClient.disconnect();
- } catch (MqttException e) {
- e.printStackTrace();
- }
- }
下面就是连接成功后的效果图
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。