利用ActiveMQ使用mqttv3发消息Android接收消息

来源:互联网 发布:ubuntu u盘安装工具 编辑:程序博客网 时间:2024/06/07 16:21

在Linux服务器端安装好并启动ActiveMQ后使用

一、发送消息

public interface PushCallBack {    int saveOnDone(boolean isOk);}
import org.eclipse.paho.client.mqttv3.*;import org.eclipse.paho.client.mqttv3.persist.MqttDefaultFilePersistence;public class MQTT {    private String host = "tcp://192.168.0.1:1883";    private String userName = "admin";    private String passWord = "admin";    private MqttClient client = null;    public static void main(String[] args) {        //发送消息        MQTT mq = new MQTT();        mq.passWord = "admin";        for (int i = 0; i < 2; i++) {            mq.send("Jaycekon-MQ", "HelloTest" + i, new PushCallBack() {                @Override                public int saveOnDone(boolean isOk) {                    System.out.println("MQTT.main(...).new PushCallBack() {...}.saveOnDone()");                    return 0;                }            });        }    }    private static MQTT mqtt = null;    public static MQTT get() {        if (mqtt == null) {            mqtt = new MQTT();        }        return mqtt;    }    private MQTT() {        init();    }    private void init() {        try {            String clientid = MqttClient.generateClientId();            if (clientid.length() > 23) {                clientid = clientid.substring(clientid.length() - 23);            }            client = new MqttClient(host, clientid,                    new MqttDefaultFilePersistence());            MqttConnectOptions options = new MqttConnectOptions();            options.setCleanSession(false);            options.setUserName(userName);            options.setPassword(passWord.toCharArray());            options.setConnectionTimeout(10);            options.setKeepAliveInterval(20);            client.setCallback(new MqttCallback() {                @Override                public void connectionLost(Throwable cause) {                    System.out                            .println("MqttCallback connectionLost-----------连接丢失");                }                @Override                public void deliveryComplete(IMqttDeliveryToken token) {                    System.out                            .println("MqttCallback deliveryComplete---------交付完成"                                    + token.getMessageId()                                    + "|"                                    + token.isComplete());                }                @Override                public void messageArrived(String topic, MqttMessage arg1)                        throws Exception {                    System.out                            .println("MqttCallback messageArrived----------消息到达");                }            });            client.connect(options);        } catch (Exception e) {            e.printStackTrace();        }    }    private void close() {        try {            if (client != null) {                client.close();                client = null;            }        } catch (Exception e) {            e.printStackTrace();        }    }    public void send(final String topics, final String notify,            PushCallBack pushCallBack) {        send(topics, notify, 1, pushCallBack);    }    private void send(final String topics, final String notify,            final int trycnt, final PushCallBack pushCallBack) {        try {            MqttDeliveryToken token;            MqttMessage message;            MqttTopic topic = client.getTopic(topics);            message = new MqttMessage();            message.setQos(2);            message.setRetained(true);            message.setPayload(notify.getBytes("UTF-8"));            token = topic.publish(message);            final int msgid = token.getMessageId();            System.out                    .println(message.isRetained() + "------ratained|" + msgid);            token.setActionCallback(new IMqttActionListener() {                @Override                public void onFailure(IMqttToken arg0, Throwable arg1) {                    if (pushCallBack != null) {                        pushCallBack.saveOnDone(false);                    }                    System.out.println(msgid + "------ActionCallback false");                }                @Override                public void onSuccess(IMqttToken arg0) {                    if (pushCallBack != null)                        pushCallBack.saveOnDone(true);                    System.out.println(msgid + "------ActionCallback true");                }            });            token.waitForCompletion();        } catch (Exception e) {            if (trycnt < 2) {// 继续尝试一次                close();                init();                send(topics, notify, trycnt + 1, pushCallBack);            } else {                e.printStackTrace();            }        }    }}

二、Android接收消息

public class MainActivity extends Activity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        Intent intent = new Intent(this, MQTTService.class);        startService(intent);    }}
package com.lgz.mq;import android.app.Service;import android.content.Intent;import android.os.IBinder;import android.widget.Toast;import org.eclipse.paho.client.mqttv3.MqttClient;import org.eclipse.paho.client.mqttv3.MqttConnectOptions;import org.eclipse.paho.client.mqttv3.MqttException;import org.eclipse.paho.client.mqttv3.MqttTopic;import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;public class MQTTService extends Service {    //消息服务器的URL    public static final String BROKER_URL = "tcp://192.168.199.174:1883";    //客户端ID,用来标识一个客户,可以根据不同的策略来生成    public static final String clientId = "admin";    //订阅的主题名    public static final String TOPIC = "Jaycekon-MQ";    //mqtt客户端类    private MqttClient mqttClient;    //mqtt连接配置类    private MqttConnectOptions options;    private String userName = "admin";    private String passWord = "admin";    public IBinder onBind(Intent intent) {        return null;    }    @Override    public int onStartCommand(Intent intent, int flags, int startId) {        try {            //在服务开始时new一个mqttClient实例,客户端ID为clientId,第三个参数说明是持久化客户端,如果是null则是非持久化            mqttClient = new MqttClient(BROKER_URL, clientId, new MemoryPersistence());            // MQTT的连接设置            options = new MqttConnectOptions();            // 设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录,这里设置为true表示每次连接到服务器都以新的身份连接            //换而言之,设置为false时可以客户端可以接受离线消息            options.setCleanSession(false);            // 设置连接的用户名            options.setUserName(userName);            // 设置连接的密码            options.setPassword(passWord.toCharArray());            // 设置超时时间 单位为秒            options.setConnectionTimeout(10);            // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线,但这个方法并没有重连的机制            options.setKeepAliveInterval(20);            // 设置回调  回调类的说明看后面            mqttClient.setCallback(new PushCallback());            MqttTopic topic = mqttClient.getTopic(TOPIC);            //setWill方法,如果项目中需要知道客户端是否掉线可以调用该方法。设置最终端口的通知消息            options.setWill(topic, "close".getBytes(), 2, true);            //mqtt客户端连接服务器            mqttClient.connect(options);            //mqtt客户端订阅主题            //在mqtt中用QoS来标识服务质量            //QoS=0时,报文最多发送一次,有可能丢失            //QoS=1时,报文至少发送一次,有可能重复            //QoS=2时,报文只发送一次,并且确保消息只到达一次。            int[] Qos = {1};            String[] topic1 = {TOPIC};            mqttClient.subscribe(topic1, Qos);        } catch (MqttException e) {            Toast.makeText(getApplicationContext(), "Something went wrong!" + e.getMessage(), Toast.LENGTH_LONG).show();            e.printStackTrace();        }        return super.onStartCommand(intent, flags, startId);    }    @Override    public void onDestroy() {        try {            mqttClient.disconnect(0);        } catch (MqttException e) {            Toast.makeText(getApplicationContext(), "Something went wrong!" + e.getMessage(), Toast.LENGTH_LONG).show();            e.printStackTrace();        }    }}
package com.lgz.mq;import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;import org.eclipse.paho.client.mqttv3.MqttCallback;import org.eclipse.paho.client.mqttv3.MqttMessage;public class PushCallback implements MqttCallback {    @Override    public void connectionLost(Throwable cause) {        System.out.println("连接失败---");    }    @Override    public void messageArrived(String topic, MqttMessage message) throws Exception {        System.out.println(" 有新消息到达时的回调方法");        System.out.println(" topic = " + topic);        String msg = new String(message.getPayload());        System.out.println("msg = " + msg);        System.out.println("qos = " + message.getQos());    }    @Override    public void deliveryComplete(IMqttDeliveryToken token) {        System.out.println("--deliveryComplete--成功发布某一消息后的回调方法");    }}

别忘了在AndroidManifest.xml中添加服务和网络权限等

<uses-permission android:name="android.permission.INTERNET" />    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />    <application        android:allowBackup="true"        android:icon="@mipmap/ic_launcher"        android:label="@string/app_name"        android:supportsRtl="true"        android:theme="@style/AppTheme">        <activity android:name=".MainActivity">            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>        <service android:name=".MQTTService" />    </application>

附件 mqttv3.jar下载

阅读全文
'); })();
0 0
原创粉丝点击
热门IT博客
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 什么人不能吃辡木籽 辡椒 小辡椒 辣妈的意思 辣爸甜妈 辣妈妈 辣妈 辣妈正传 隔壁辣妈中文字幕 辣妈计划 上海辣妈 辣妈帮 电臀辣妈 朋友辣妈 41岁辣妈与14岁儿子 辣妈孕妇季玥137张图片 邻居辣妈 辣妈正传图片 上海辣妈番外篇 amanda辣妈母乳资源 辣妈正传演员表 47岁旗袍辣妈被老外频图片 辣妈正传续写怀孕 辣妈图片 什么是辣妈 辣妈什么意思 辣妈是什么意思 瘦客辣妈减肥原理 辣妈帮怎么加好友 辣妈网 辣妈瘦身 天才宝宝小辣妈 辣妈帮app 时尚辣妈亲子照 时尚辣妈产后恢复中心 辣妈减肥 辣妈团 辣妈amanda 辣爸辣妈 辣妈团购网 性感辣妈