首页 > 解决方案 > 尝试连接到 MQTT 服务器但服务器未运行时关闭应用程序

问题描述

下午好,我创建了一个服务来监听 MQTT 代理服务器,但是当我启动应用程序并且服务器未处于活动状态时,它正在关闭应用程序,当我激活 MQTT 服务器并打开应用程序时,它运行良好。连接到服务器的代码块已经实现了 try/catch,但即便如此它最终还是关闭了应用程序。

在服务类中,我执行以下代码:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.i("onStartCommand", "onStartCommand");
    try {
        try {
            this.MQTTServer = new MQTTServer(this);
            this.MQTTServer.init(new GenericCode.BooleanCode() {
                @Override
                public void booleanCode(boolean connected) {}
            });
        } catch (Exception e) {
            e.printStackTrace();
        }


    } catch(Exception e){
        e.printStackTrace();
    }

    return super.onStartCommand(intent, flags, startId);
}

服务器未运行时的错误消息:

2020-08-31 11:05:33.172 3099-3099/com.example.ktrine E/ActivityThread: Service com.example.ktrine.service.NotificationService has leaked ServiceConnection org.eclipse.paho.android.service.MqttAndroidClient$MyServiceConnection@8c9622a that was originally bound here
android.app.ServiceConnectionLeaked: Service com.example.ktrine.service.NotificationService has leaked ServiceConnection org.eclipse.paho.android.service.MqttAndroidClient$MyServiceConnection@8c9622a that was originally bound here
    at android.app.LoadedApk$ServiceDispatcher.<init>(LoadedApk.java:1541)
    at android.app.LoadedApk.getServiceDispatcher(LoadedApk.java:1433)
    at android.app.ContextImpl.bindServiceCommon(ContextImpl.java:1620)
    at android.app.ContextImpl.bindService(ContextImpl.java:1572)
    at android.content.ContextWrapper.bindService(ContextWrapper.java:684)
    at org.eclipse.paho.android.service.MqttAndroidClient.connect(MqttAndroidClient.java:420)
    at org.eclipse.paho.android.service.MqttAndroidClient.connect(MqttAndroidClient.java:354)
    at org.eclipse.paho.android.service.MqttAndroidClient.connect(MqttAndroidClient.java:309)
    at com.example.ktrine.server.MQTTServer.init(MQTTServer.java:34)
    at com.example.ktrine.service.NotificationService.onStartCommand(NotificationService.java:39)

即使代码块有一个 try/catch,它也会关闭应用程序。这与在后台运行的服务有什么关系吗?

标签: androidandroid-studiomqttpaho

解决方案


推荐阅读