Android:我的mqtt服务器没有断开连接

时间:2013-12-31 07:53:47

标签: java android protocols mqtt

当用户杀死应用程序时,我的mqtt服务器不会断开连接。还有其他用户可以看到状态在线。关闭应用程序后,我需要断开mqtt服务器。

1)我的第一次连接成功

2)关闭应用程序后,mqtt不会断开连接

3)如果有人发送了消息,它会再次自动订阅

private static BroadcastReceiver receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (LBUtil.isNetworkAvailable(context)) {
            if (BuildConfig.DEBUG) {
                LBLog.v(TAG, "network is available now");
            }

        }
    }
};

@Override
public IBinder onBind(Intent arg0) {
    return null;
}

这里启动mqtt服务。

@Override
public void onCreate() {
    super.onCreate();
    LBLog.v(TAG, "start mqtt service");

    mApp = (LBApplication) this.getApplicationContext();
    mHandler = LBMessageManager.messageHandler;
    mServerUri = LBUtil.getMqttBrokerUrl(this);

    // register re-subscribe listener
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(LBMessageManager.ACTION_MQTT_SUBSCRIBE);

    receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            LBLog.v(TAG, "re-subscribe mqtt");
            isConnected = false;
            if(!mMqttClient.isConnected()){
                subscribeMqttTopic();               
            }


        }
    };
    registerReceiver(receiver, intentFilter);

    subscribeMqttTopic();
}

private void subscribeMqttTopic() {

    subscriberThread = new Thread(new Runnable() {
        public void run() {

            do {
                try {
                    mClientId = mApp.getDeviceToken() == null? mApp.getAuthToken():mApp.getDeviceToken();
                    mTopic = mApp.getSecretKey() + mApp.getUserId();
                    mWillTopic = mApp.getSecretKey() + mApp.getPartnerId();

                    if(mServerUri == null){
                        LBLog.e(TAG, "mServerUri is null");
                    }
                    if(mClientId == null){
                        LBLog.e(TAG, "mClientId is null");
                    }

                    if(mMqttClient == null){
                        mMqttClient = new MqttClient(mServerUri, mClientId, null);
                    }

                    Messenger messenger = new Messenger(mHandler);
                    LBMessageCallback callback = new LBMessageCallback(mApp, messenger);

                    mMqttClient.setCallback(callback);

                    final MqttConnectOptions options = new MqttConnectOptions();
                    options.setCleanSession(false);
                    options.setUserName(LBUtil.getMqttServerUsername(mApp));
                    options.setPassword(LBUtil.getMqttServerPassword(mApp).toCharArray());

                    // set will message
                    LBMqttMessage mqttMessage = new LBMqttMessage();
                    mqttMessage.setFrom(mApp.getUserId());
                    mqttMessage.setTo(mApp.getPartnerId());
                    mqttMessage.setType(LBMessageManager.TYPE_STATUS);
                    mqttMessage.setState(LBMessageManager.STATE_INACTIVE);

                    ObjectMapper mapper = new ObjectMapper();
                    mapper.registerModule(new JodaModule());

                    String jsonString = null;
                    try {
                        FilterProvider filters = new SimpleFilterProvider().addFilter("lbMqttMessageFilter", SimpleBeanPropertyFilter.filterOutAllExcept("state", "to", "from"));
                        jsonString = mapper.writer(filters).writeValueAsString(mqttMessage);
                        LBLog.v(TAG, "will message=" + jsonString);
                    } catch (JsonProcessingException e) {
                        LBLog.e(TAG, "enableMqtt", e);
                    }

                    options.setWill(mMqttClient.getTopic(mWillTopic), jsonString.getBytes(), LBMessageMqtt.QOS_1, false);

                    // connect
                    mMqttClient.connect(options);

                    // subscribe
                    LBLog.v(TAG, "Subscribing mTopic=" + mTopic);
                    mMqttClient.subscribe(mTopic);

                    LBLog.v(TAG, "subscribe success");
                    isConnected = true;

                } catch (MqttException e) {
                    Log.v(TAG, e.toString());
                    isConnected = false;

                    try { // wait some time before retry
                        Thread.sleep(5000);
                    } catch (InterruptedException e1) {
                        Log.v(TAG, e1.toString());
                    }

                }
            } while (isConnected == false);

        }
    });

    subscriberThread.start();

}

@Override
public void onDestroy() {
    super.onDestroy();
    LBLog.v(TAG, "destroying mqtt service...");
    unregisterReceiver(receiver);
    if(mMqttClient != null && mMqttClient.isConnected()){
        try {
            mMqttClient.disconnect();
        } catch (MqttException e) {
            LBLog.e(TAG, "onDestroy", e);
        }
    }
}

}

1 个答案:

答案 0 :(得分:0)

退出应用程序时,您应手动完成服务。此外,广播中还有一个电话,我们看不到它的代码。

LBUtil.isNetworkAvailable(context)

确保此内容无法再次启动您的服务。