从飞机模式重新连接到MQTT Android服务

时间:2015-02-16 17:24:55

标签: java android service mqtt

我正在实现此处http://dalelane.co.uk/blog/?p=1599中发现的Dale Lane MQTT Android服务示例,该示例对我的特定目的非常有效,但我正在处理一个我似乎无法解决的问题。

经过相当广泛的测试后,我发现手机完全断开连接后服务无法重新连接。例如,如果手机处于飞行模式,然后退出飞行模式,服务将继续尝试connectToBroker(),但永远不会连接。

如果我按下" connect"应用程序正确连接。主屏幕上的按钮,用给定的主机/主题参数启动服务。

如何解决此问题?该应用程序没有问题从Wifi网络重新连接,反之亦然。

02-16 12:19:39.348: E/mqtt(23628): ping failed - MQTT exception
02-16 12:19:39.348: E/mqtt(23628): com.ibm.mqtt.MqttNotConnectedException
02-16 12:19:39.348: E/mqtt(23628):  at com.ibm.mqtt.Mqtt.writePacket(Unknown Source)
02-16 12:19:39.348: E/mqtt(23628):  at com.ibm.mqtt.Mqtt.pingOut(Unknown Source)
02-16 12:19:39.348: E/mqtt(23628):  at com.ibm.mqtt.MqttClient.ping(Unknown Source)
02-16 12:19:39.348: E/mqtt(23628):  at com.limosys.limosystestmqtt.MQTTService$PingSender.onReceive(MQTTService.java:919)
02-16 12:19:39.348: E/mqtt(23628):  at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:778)
02-16 12:19:39.348: E/mqtt(23628):  at android.os.Handler.handleCallback(Handler.java:733)
02-16 12:19:39.348: E/mqtt(23628):  at android.os.Handler.dispatchMessage(Handler.java:95)
02-16 12:19:39.348: E/mqtt(23628):  at android.os.Looper.loop(Looper.java:136)
02-16 12:19:39.348: E/mqtt(23628):  at android.app.ActivityThread.main(ActivityThread.java:5105)
02-16 12:19:39.348: E/mqtt(23628):  at java.lang.reflect.Method.invokeNative(Native Method)
02-16 12:19:39.348: E/mqtt(23628):  at java.lang.reflect.Method.invoke(Method.java:515)
02-16 12:19:39.348: E/mqtt(23628):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:792)
02-16 12:19:39.348: E/mqtt(23628):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:608)
02-16 12:19:39.348: E/mqtt(23628):  at dalvik.system.NativeStart.main(Native Method)

如果ping失败,则抛出异常的堆栈跟踪,应用程序继续尝试根据给定的keepAliveSecond值每10秒连接一次。

CONNECTIONLOST

/*
   * callback - method called when we no longer have a connection to the message broker server
   */
  public void connectionLost() throws Exception {
    // we protect against the phone switching off while we're doing this
    // by requesting a wake lock - we request the minimum possible wake
    // lock - just enough to keep the CPU running until we've finished
    PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
    WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MQTT");
    wl.acquire();


    //
    // have we lost our data connection?
    //

    if (isOnline() == false) {
      Log.e("CONNECTION LOST", "LOST CONNECTION");
      connectionStatus = MQTTConnectionStatus.NOTCONNECTED_WAITINGFORINTERNET;

      // inform the app that we are not connected any more
      broadcastServiceStatus("Connection lost - no network connection");

      //
      // inform the user (for times when the Activity UI isn't running)
      // that we are no longer able to receive messages
      notifyUser("Connection lost - no network connection", "MQTT",
          "Connection lost - no network connection");

      //
      // wait until the phone has a network connection again, when we
      // the network connection receiver will fire, and attempt another
      // connection to the broker
    } else {
      //
      // we are still online
      // the most likely reason for this connectionLost is that we've
      // switched from wifi to cell, or vice versa
      // so we try to reconnect immediately
      //

      connectionStatus = MQTTConnectionStatus.NOTCONNECTED_UNKNOWNREASON;

      // inform the app that we are not connected any more, and are
      // attempting to reconnect
      broadcastServiceStatus("Connection lost - reconnecting...");

      // try to reconnect
      if (connectToBroker()) {
        subscribeToTopic(topicName);
      }
    }

    // we're finished - if the phone is switched off, it's okay for the CPU
    // to sleep now
    wl.release();
  }

连接到经纪人 服务可用后(即退出飞机模式并连接到4G / Wifi),会多次调用此代码。

 /*
   * (Re-)connect to the message broker
   */
  private boolean connectToBroker() {
    try {
      // try to connect
      Log.e("CONNECTTOBROKER", "TRYING TO CONNECT");
      Log.e("SERVICE HOST - CONNECT TO BROKER", "" + brokerHostName);
      Log.e("SERVICE TOPIC - CONNECT TO BROKER", "" + topicName);

      mqttClient.connect(generateClientId(), cleanStart, keepAliveSeconds);

      //
      // inform the app that the app has successfully connected
      broadcastServiceStatus("Connected");

      // we are connected
      connectionStatus = MQTTConnectionStatus.CONNECTED;

      // we need to wake up the phone's CPU frequently enough so that the
      // keep alive messages can be sent
      // we schedule the first one of these now
      scheduleNextPing();


      return true;
    } catch (MqttException e) {
      // something went wrong!

      connectionStatus = MQTTConnectionStatus.NOTCONNECTED_UNKNOWNREASON;

      //
      // inform the app that we failed to connect so that it can update
      // the UI accordingly
      broadcastServiceStatus("Unable to connect");

      //
      // inform the user (for times when the Activity UI isn't running)
      // that we failed to connect
      notifyUser("Unable to connect", "MQTT", "Unable to connect - will retry later");

      // if something has failed, we wait for one keep-alive period before
      // trying again
      // in a real implementation, you would probably want to keep count
      // of how many times you attempt this, and stop trying after a
      // certain number, or length of time - rather than keep trying
      // forever.
      // a failure is often an intermittent network issue, however, so
      // some limited retry is a good idea
      scheduleNextPing();

      return false;
    }
  }

1 个答案:

答案 0 :(得分:3)

从paho下载最新的android服务jar(1.02)和java客户端(1.02)。 最新的Android服务jar解决了这个问题。一旦网络连接恢复,它就会重新连接。

将此内容添加到Activity

的onResume()中
mqttclient.registerResources(this);     

并且在同一个Activity的onDestroy()里面

mqttclient.unregisterResources();

这对我有用。