Paho Mqtt Android客户端在Android中没有收到任何消息

时间:2017-01-20 20:42:28

标签: android mqtt

我有Mqtt Android客户端,代码来源

import android.annotation.SuppressLint;
import android.content.Context;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;

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.MqttCallbackExtended;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;

import java.util.Arrays;

import horseman.four.com.unite.app.UniteApp;
import horseman.four.com.unite.screens.map.ChatManager;
import horseman.four.com.unite.screens.map.model.ChatMessage;
import horseman.four.com.unite.screens.map.model.ChatModel;

/**
 * Created by Mahendra Chhimwal on 18/1/17.
 */

public class MqttManager implements MqttCallbackExtended {

    public static final String TAG = "MqttManager";

    private MqttAndroidClient mMqttAndroidClient;
    private MqttAndroidClient mMqttAndroidReceiver;

    private final String mServerUri = "tcp://unitevm.eastus.cloudapp.azure.com:1883";

    private String mClientId = null;
    private final String mSubscriptionTopic = "exampleAndroidTopic";
    private final String mPublishTopic = "exampleAndroidPublishTopic";
    private final String mPublishMessage = "Hello World!";

    private ChatManager mChatManager;
    private Context mContext;
    private String mTopic;

    private static Gson GSON = new Gson();

    private MqttManager() {
        mContext = UniteApp.getContext();
    }

    public static MqttManager getINST() {
        return new MqttManager();
    }

    public void setChatManager(@NonNull ChatManager chatManager) {
        mChatManager = chatManager;
    }

    @SuppressLint("HardwareIds")
    public void initConnection(String topic) {
        mTopic = topic;
        mClientId = Settings.Secure.getString(mContext.getContentResolver(),
                Settings.Secure.ANDROID_ID);
        mMqttAndroidClient = new MqttAndroidClient(mContext, mServerUri, mClientId);
        mMqttAndroidReceiver = new MqttAndroidClient(mContext, mServerUri, "csajcbjsc");
        mMqttAndroidClient.setCallback(this);
        mMqttAndroidReceiver.setCallback(this);
        connectToServer();
    }

    @Override
    public void connectComplete(boolean reconnect, String serverURI) {
        if (reconnect) {
            Log.d(TAG, "reconnect is true . So subscribing to topic again");
            // Because Clean Session is true, we need to re-subscribe
            subscribeToTopic();
        } else {
            Log.d(TAG, "Connected to MQTT server");
        }
    }

    private void connectToServer() {

        MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
        mqttConnectOptions.setAutomaticReconnect(true);
        mqttConnectOptions.setCleanSession(false);
        mqttConnectOptions.setKeepAliveInterval(300);
        mqttConnectOptions.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1);
        try {
            mMqttAndroidClient.connect(mqttConnectOptions, null, new IMqttActionListener() {
                @Override
                public void onSuccess(IMqttToken asyncActionToken) {
                    Log.d(TAG, "mqtt connect successfull. Now Subscribing to topic...");
                    subscribeToTopic();
                }

                @Override
                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                    if (exception != null) {
                        Log.e(TAG, "connect failure with exception : " + exception.getMessage());
                        exception.printStackTrace();
                    }
                }
            });

        } catch (MqttException ex) {
            ex.printStackTrace();

        }





        MqttConnectOptions mqttConnectOption = new MqttConnectOptions();
        mqttConnectOption.setAutomaticReconnect(true);
        mqttConnectOption.setCleanSession(false);
        mqttConnectOption.setKeepAliveInterval(300);
        mqttConnectOption.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1);
        try {
            mMqttAndroidReceiver.connect(mqttConnectOptions, null, new IMqttActionListener() {
                @Override
                public void onSuccess(IMqttToken asyncActionToken) {
                    Log.d(TAG, "mqtt connect successfull. Now Subscribing to topic...");
                    subscribeToTopic();
                }

                @Override
                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                    if (exception != null) {
                        Log.e(TAG, "connect failure with exception : " + exception.getMessage());
                        exception.printStackTrace();
                    }
                }
            });

        } catch (MqttException ex) {
            ex.printStackTrace();

        }
    }

    @Override
    public void connectionLost(Throwable cause) {
        if (cause != null) {
            Log.e(TAG, "Connection to MQtt is lost due to " + cause.getMessage());
        }
        // connectToServer();
    }

    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {
        Log.d(TAG, "Message arrived : " + message + " from topic : " + topic);
        if (mTopic.equals(topic)) {
            String text = message.toString();
            if (!TextUtils.isEmpty(text)) {
                handlerChatMessage(text);
            }
        }
    }

    private void handlerChatMessage(String message) {
        try {
            ChatModel chatModel = GSON.fromJson(message, ChatModel.class);
            if (chatModel.isChat()) {
                String chatMessage = chatModel.getMessage();
                if (!TextUtils.isEmpty(chatMessage)) {
                    ChatMessage cMessageObj = GSON.fromJson(chatMessage, ChatMessage.class);
                    cMessageObj.setSenderId(chatModel.getSender());
                    if (mChatManager != null) {
                        mChatManager.chatMessageArrived(cMessageObj);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
        try {
            if (token != null && token.getMessage() != null) {
                Log.d(TAG, "Message : " + token.getMessage().toString() + " delivered");
            }
        } catch (MqttException ex) {
            ex.printStackTrace();
        }
    }


    private void subscribeToTopic() {
        try {
            mMqttAndroidClient.subscribe(mTopic, 0, null, new IMqttActionListener() {
                @Override
                public void onSuccess(IMqttToken asyncActionToken) {
                    Log.d(TAG, "Subscribed to topic : " + mTopic);
                }

                @Override
                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                    Log.d(TAG, "topic subscription failed for topic : " + mTopic);
                }
            });

        } catch (MqttException ex) {
            System.err.println("Exception whilst subscribing");
            ex.printStackTrace();
        }
    }


    public void publishMessage(String messageText) {

        try {
            MqttMessage message = new MqttMessage();
            message.setPayload(messageText.getBytes());
            message.setQos(2);
            mMqttAndroidClient.publish(mPublishTopic, message);
            if (!mMqttAndroidClient.isConnected()) {
            }
        } catch (MqttException e) {
            System.err.println("Error Publishing: " + e.getMessage());
            e.printStackTrace();
        }
    }

}

Adb记录来自客户端的发布事件

01-21 02:03:47.581 17426-18022/horseman.four.com.unite D/AlarmPingSender: Register alarmreceiver to MqttServiceMqttService.pingSender.aae59bad799dafed
01-21 02:03:47.581 17426-18021/horseman.four.com.unite D/AlarmPingSender: Register alarmreceiver to MqttServiceMqttService.pingSender.csajcbjsc
01-21 02:03:47.620 17426-17426/horseman.four.com.unite D/MqttManager: mqtt connect successfull. Now Subscribing to topic...
01-21 02:03:47.632 17426-17426/horseman.four.com.unite D/MqttManager: mqtt connect successfull. Now Subscribing to topic...
01-21 02:03:47.895 17426-17426/horseman.four.com.unite D/MqttManager: Subscribed to topic : example_topic
01-21 02:03:48.250 17426-17426/horseman.four.com.unite D/MqttManager: Subscribed to topic : example_topic
01-21 02:03:54.859 17426-17426/horseman.four.com.unite D/MqttManager: Message : jcjcf delivered
01-21 02:03:56.087 17426-17426/horseman.four.com.unite D/MqttManager: Message : vjchxhf delivered
01-21 02:03:57.407 17426-17426/horseman.four.com.unite D/MqttManager: Message : jcjcufi delivered
01-21 02:03:58.342 17426-17426/horseman.four.com.unite D/MqttManager: Message : jchxuf delivered
01-21 02:03:59.267 17426-17426/horseman.four.com.unite D/MqttManager: Message : gjcjf delivered
01-21 02:04:00.089 17426-17426/horseman.four.com.unite D/MqttManager: Message : gjcig delivered
01-21 02:04:01.004 17426-17426/horseman.four.com.unite D/MqttManager: Message : gjcif delivered
01-21 02:04:01.819 17426-17426/horseman.four.com.unite D/MqttManager: Message : gjgiy delivered
01-21 02:04:02.839 17426-17426/horseman.four.com.unite D/MqttManager: Message : gjgiy delivered
01-21 02:04:03.457 17426-17426/horseman.four.com.unite D/MqttManager: Message : gjfjg delivered
01-21 02:04:04.378 17426-17426/horseman.four.com.unite D/MqttManager: Message : gjfiu delivered
01-21 02:04:21.478 17426-17426/horseman.four.com.unite D/MqttManager: Message : vghbng v gjc delivered
01-21 02:04:22.912 17426-17426/horseman.four.com.unite D/MqttManager: Message : bvcucjh delivered
01-21 02:04:24.140 17426-17426/horseman.four.com.unite D/MqttManager: Message : gjcjv delivered

任何人都可以帮助我找出我在这里缺少的东西吗?接收器没有收到任何消息,因为从日志中可以清楚地看到它。

1 个答案:

答案 0 :(得分:1)

您已订阅example_topic(或通过initConnection()mTopic设置的任何内容),但您要发布到exampleAndroidPublishTopic,这是const {{1}的固定值}}