MQTT-Android

MQTT在Android中的使用,客户端的,记录一下。

官方文档 https://github.com/eclipse/paho.mqtt.android

添加依赖

compile 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.1.0'//compile 'org.eclipse.paho:org.eclipse.paho.android.service:1.0.2@arr'

compile 'org.greenrobot:eventbus:3.0.0'

添加完之后,可能会出现warning:

ignoring innerclasses attribute for an anonymous inner class

处理方法是在 proguard-rules.pro,中添加

-keepattributes InnerClasses

-keepattributes EnclosingMethod

-dontoptimize

这个问题的处理可参考 http://stackoverflow.com/questions/35796144/progaurd-issue-warningignoring-innerclasses-attribute-for-an-anonymous-inner-c

使用

基本使用,可参考以下博客,很详细

博客地址:http://www.longdw.com/mqtt-server-client-android/

下面是部分代码:

private void init() {
        try {
                       //host为主机名,test为clientid即连接MQTT的客户端ID,一般以客户端唯一标识符表示,MemoryPersistence设置clientid的保存形式,默认为以内存保存
            client = new MqttClient(host, "test",
                    new MemoryPersistence());
                       //MQTT的连接设置
            options = new MqttConnectOptions();
                       //设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录,这里设置为true表示每次连接到服务器都以新的身份连接
            options.setCleanSession(true);
                       //设置连接的用户名
            options.setUserName(userName);
                       //设置连接的密码
            options.setPassword(passWord.toCharArray());
            // 设置超时时间 单位为秒
            options.setConnectionTimeout(10);
            // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线,但这个方法并没有重连的机制
            options.setKeepAliveInterval(20);
                        //设置回调
            client.setCallback(new MqttCallback() {

                @Override
                public void connectionLost(Throwable cause) {
                                        //连接丢失后,一般在这里面进行重连
                    System.out.println("connectionLost----------");
                }

                @Override
                public void deliveryComplete(IMqttDeliveryToken token) {
                                        //publish后会执行到这里
                    System.out.println("deliveryComplete---------"
                            + token.isComplete());
                }

                @Override
                public void messageArrived(String topicName, MqttMessage message)
                        throws Exception {
                                        //subscribe后得到的消息会执行到这里面
                    System.out.println("messageArrived----------");
                }
            });
//            connect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值