安卓MQTT协议的的使用,并使用protobuf协议传输数据

1,导入2个jar包

2,在AndroidManifest中添加Service

<service android:name="org.eclipse.paho.android.service.MqttService" />

然后在代码中定义自己的Servce.例如我的叫:MQTTService

3,在我们服务启动的时候调用init方法进行初始化MQTT各种操作


    private void init() {
        String uri = host;
        client = new MqttAndroidClient(getApplicationContext(), uri, clientId);
        // 设置MQTT监听并且接受消息
        client.setCallback(mqttCallback);

        conOpt = new MqttConnectOptions();
        // 清除缓存
        conOpt.setCleanSession(true);
        // 设置超时时间,单位:秒
        conOpt.setConnectionTimeout(20);
        // 心跳包发送间隔,单位:秒
        conOpt.setKeepAliveInterval(3 * 60);
        // 用户名
        conOpt.setUserName(userName);
        // 密码
        conOpt.setPassword(passWord.toCharArray());     //将字符串转换为字符串数组
        //断开后,是否自动连接
        conOpt.setAutomaticReconnect(true);

        // last will message
        boolean doConnect = true;
        String message = "{\"clientId\":\"" + clientId + "\"}";
        Log.e(getClass().getName(), "message is:" + message);
        String topic = "track";
        Integer qos = 1;
        Boolean retained = false;
        if ((!message.equals("")) || (!topic.equals(""))) {
            // 最后的遗嘱
            // MQTT本身就是为信号不稳定的网络设计的,所以难免一些客户端会无故的和Broker断开连接。
            //当客户端连接到Broker时,可以指定LWT,Broker会定期检测客户端是否有异常。
            //当客户端异常掉线时,Broker就往连接时指定的topic里推送当时指定的LWT消息。
            try {
                conOpt.setWill("public", message.getBytes(), 1, retained.booleanValue());
//                conOpt.setWill("e-wallet", message.getBytes(), 2, retained.booleanValue());
            } catch (Exception e) {
                Log.e(TAG, "Exception Occured", e);
                doConnect = false;
                iMqttActionListener.onFailure(null, e);
            }
        }

        if (doConnect) {
            doClientConnection();
        }

    }

 其中userName  passWord和host是与后台商量一致的

前面的工作往后才能后,我们就去调用doClientConnection连接mqtt服务,为了防止重复连接我们添加一个标志位doConnect


    /**
     * 连接MQTT服务器
     */
    private void doClientConnection() {
        if (!client.isConnected()) {
            try {
                client.connect(conOpt, null, iMqttActionListener);
         
  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值