Paho MQTT Android Service Issue

后端 未结 4 1699
离开以前
离开以前 2020-12-30 11:56

I am implementing the Paho MQTT Android Service within an application I am developing. After testing the sample application provided by Paho, I have found that there are a f

4条回答
  •  南笙
    南笙 (楼主)
    2020-12-30 12:03

    If you close your app using the task manager I don't think this is possible since "fully closing" the app will also stop any services it contains. Even though the service is started "sticky" it does not re-launch on my device. If you close the app by swiping it away on the recent tasks the service does remain running. See here for more info: Killing android application from task manager kills services started by app

    However, I think the other problem is even if the service is still running the application contains the callback objects that get invoked by the service. If the application is no longer running the callback no longer exists and thus never gets called.

    Here is a high level view of how I implemented this. This has been running in production for a few months but unfortunately I don't own the code and can't post it.

    • I created a singleton object that hosts the MQTTService/mqttAndroidClient. This exposes public methods to connect/disconnect, and contains the MqttCallback object used to receive the messages. It also handles the connection lost and retry mechanisms needed. This is the trickiest part but I can't post it here.
    • I created an Application object, I connect in onCreate() and close the connection in onTerminate()
    • I registered a BroadcastReceiver that gets the BOOT_COMPLETED action that resides in the Application object, it has an empty implementation but it spins up the application so the mqtt service connects on boot.

    This eliminates the need for any given activity to be running to receive a message. It also seems resilient against closing the application, the exception being if you 'force close' it in the application settings. That makes since though since the user explicitly chose to close it.

提交回复
热议问题