Android Mqtt 訊息推送使用

來源:互聯網
上載者:User

標籤:gate   new   tin   zed   message   action   subscript   localize   使用   

初始化SDK:

/**     * 初始化SDK     *     * @param context context     */    public void initSDK(Context context) {        String clientId = String.valueOf(System.currentTimeMillis()+userId);        mqttAndroidClient = new MqttAndroidClient(mContext, serverUri, clientId);        subscriptionTopics = new ArrayList<>();        mqttAndroidClient.setCallback(new MqttCallbackExtended() {            @Override            public void connectComplete(boolean reconnect, String serverURI) {                if (reconnect) {                    Log.d(TAG, "Reconnected to : " + serverURI);                    // Because Clean Session is true, we need to re-subscribe//                    subscribeToTopic();                    //publishMessage();                } else {                    Log.d(TAG, "Connected to: " + serverURI);                }                connectSuccess = true;                subscribeToTopic();            }            @Override            public void connectionLost(Throwable cause) {                connectSuccess = false;                Log.e(TAG, "The Connection was lost." + cause.getLocalizedMessage());            }            // THIS DOES NOT WORK!            @Override            public void messageArrived(String topic, MqttMessage message) throws Exception {                Log.d(TAG, "Incoming message: " +topic+ new String(message.getPayload()));            }            @Override            public void deliveryComplete(IMqttDeliveryToken token) {            }        });    }

串連遠程服務:

/**     * 串連遠程服務     */    public void connectServer() {        MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();        mqttConnectOptions.setAutomaticReconnect(true);        mqttConnectOptions.setCleanSession(false);        try {            //addToHistory("Connecting to " + serverUri);            mqttAndroidClient.connect(mqttConnectOptions, null, new IMqttActionListener() {                @Override                public void onSuccess(IMqttToken asyncActionToken) {                    connectSuccess = true;                    DisconnectedBufferOptions disconnectedBufferOptions = new DisconnectedBufferOptions();                    disconnectedBufferOptions.setBufferEnabled(true);                    disconnectedBufferOptions.setBufferSize(100);                    disconnectedBufferOptions.setPersistBuffer(false);                    disconnectedBufferOptions.setDeleteOldestMessages(false);                    mqttAndroidClient.setBufferOpts(disconnectedBufferOptions);                }                @Override                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {                    Log.e(TAG, "Failed to connect to: " + serverUri);                    exception.printStackTrace();                    Log.d(TAG, "onFailure: " + exception.getCause());                    connectSuccess = false;                }            });        } catch (MqttException ex) {            ex.printStackTrace();        }    }

 

擷取訂閱資訊:

  /**     *擷取訂閱資訊
   */

public void connectGateway(String gatewayId, String userId) {
//擷取訂閱資訊        if (!subscriptionTopics.contains(gatewayId)) {            subscriptionTopics.add(gatewayId);        }        Log.d(TAG, "pre sub topic: connect status=" + connectSuccess);        Log.d(TAG, "subtopic " + subscriptionTopics);        subscribeToTopic();    }

  

訂閱mqtt訊息:

/**     * 訂閱mqtt訊息     */    private void subscribeToTopic() {        try {            if(subscriptionTopics.size()==0)                return;            String[] topics = new String[subscriptionTopics.size()];            subscriptionTopics.toArray(topics);            int[] qoc = new int[topics.length];            IMqttMessageListener[] mqttMessageListeners = new IMqttMessageListener[topics.length];            for (int i = 0; i < topics.length; i++) {                IMqttMessageListener mqttMessageListener = new IMqttMessageListener() {                    @Override                    public void messageArrived(String topic, MqttMessage message) throws Exception {                        // message Arrived!訊息送達後做出的處理                        Log.d(TAG, topic + " : " + new String(message.getPayload()));                        handleReceivedMessage(new String(message.getPayload()), topic);                    }                };                mqttMessageListeners[i] = mqttMessageListener;                Log.d(TAG, "subscribeToTopic: qoc= " + qoc[i]);            }            mqttAndroidClient.subscribe(topics, qoc, null, new IMqttActionListener() {                @Override                public void onSuccess(IMqttToken iMqttToken) {                    Log.d(TAG, "Subscribed!");                }                @Override                public void onFailure(IMqttToken iMqttToken, Throwable throwable) {                    Log.d(TAG, "Failed to subscribe");                }            }, mqttMessageListeners);        } catch (MqttException ex) {            System.err.println("Exception whilst subscribing");            ex.printStackTrace();        }    }

 

處理收到的訊息:

private void handleReceivedMessage(String message, String gatewayId) {//可以發送一條廣播通知程式}    

  

發送mqtt訊息:

/**     * 發送 mqtt 訊息     *     * @param publishMessage 要發送的資訊的 字串     */    private void publishMessage(String publishMessage, String publishTopic) {            try {                publishTopic = userId + "/" + publishTopic;                MqttMessage message = new MqttMessage();                message.setPayload(publishMessage.getBytes());                mqttAndroidClient.publish(publishTopic, message);                Log.d(TAG, "publishMessage:Message Published \n" + publishTopic + ":" + message);                if (!mqttAndroidClient.isConnected()) {                    Log.d(TAG, mqttAndroidClient.getBufferedMessageCount() + " messages in buffer.");                }            } catch (MqttException e) {                System.err.println("Error Publishing: " + e.getMessage());                e.printStackTrace();            }    }

  

 

沒有封裝的類:

public class SubscribeClient {    private final static String CONNECTION_STRING = "tcp://mqtt地址:mqtt連接埠";    private final static boolean CLEAN_START = true;    private final static short KEEP_ALIVE = 30;//低耗網路,但是又需要及時擷取資料,心跳30s    private final static String CLIENT_ID = "client1";    private final static String[] TOPICS = {            //訂閱資訊    };    private final static int[] QOS_VALUES = {0, 0, 2, 0};    private MqttClient mqttClient = null;    public SubscribeClient(String i) {        try {            mqttClient = new MqttClient(CONNECTION_STRING);            SimpleCallbackHandler simpleCallbackHandler = new SimpleCallbackHandler();            mqttClient.registerSimpleHandler(simpleCallbackHandler);//註冊接收訊息方法            mqttClient.connect(CLIENT_ID + i, CLEAN_START, KEEP_ALIVE);            mqttClient.subscribe(TOPICS, QOS_VALUES);//訂閱接主題            /**             * 完成訂閱後,可以增加心跳,保持網路通暢,也發行就緒自己的訊息             */            mqttClient.publish(PUBLISH_TOPICS, "keepalive".getBytes(), QOS_VALUES[0], true);        } catch (MqttException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }    /**     * 簡單回呼函數,處理client接收到的主題訊息     *     * @author pig     */    class SimpleCallbackHandler implements MqttSimpleCallback {        /**         * 當客戶機和broker意外斷開時觸發         * 可以再此處理重新訂閱         */        @Override        public void connectionLost() throws Exception {            // TODO Auto-generated method stub            System.out.println("客戶機和broker已經斷開");        }        /**         * 客訂閱訊息後,該方法負責回調接收處理訊息         */        @Override        public void publishArrived(String topicName, byte[] payload, int Qos, boolean retained) throws Exception {            // TODO Auto-generated method stub            System.out.println("訂閱主題: " + topicName);            System.out.println("訊息資料: " + new String(payload));            System.out.println("訊息層級(0,1,2): " + Qos);            System.out.println("是否是即時發送的訊息(false=即時,true=伺服器上保留的最後訊息): " + retained);        }    }    /**     * 進階回調     *     * @author pig     */    class AdvancedCallbackHandler implements MqttSimpleCallback {        @Override        public void connectionLost() throws Exception {            // TODO Auto-generated method stub        }        @Override        public void publishArrived(String arg0, byte[] arg1, int arg2,                                   boolean arg3) throws Exception {            // TODO Auto-generated method stub        }    }    /**     * @param args     */    public static void main(String[] args) {        // TODO Auto-generated method stub        new SubscribeClient("" + i);    }}

  

Android Mqtt 訊息推送使用

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.