From da386b2ac3062ef361a8e9e946a8322b8cf1e1e9 Mon Sep 17 00:00:00 2001 From: Jonathan Bagg Date: Thu, 4 Nov 2021 08:14:09 -0400 Subject: [PATCH] Android: Call nsd.unregisterService() synchronously when going to sleep If Android is on it's way to suspend when stopServicePublish() is called, we need to call nsd.unregisterService() synchronously to force it to run before the device goes to sleep. If instead it is scheduled to run in the Android thread, it will not run until the device is woken back up. --- androidnsd.cpp | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/androidnsd.cpp b/androidnsd.cpp index 88ab4b8..48f7733 100644 --- a/androidnsd.cpp +++ b/androidnsd.cpp @@ -24,6 +24,7 @@ NsdManager wrapper for use on Android devices --------------------------------------------------------------------------------------------------- **************************************************************************************************/ +#include #include "androidnsd_p.h" Q_DECLARE_METATYPE(QHostAddress) @@ -98,9 +99,16 @@ void QZeroConfPrivate::startServicePublish(const char *name, const char *type, q void QZeroConfPrivate::stopServicePublish() { QAndroidJniObject ref(nsdManager); - QtAndroid::runOnAndroidThread([ref]() { + // If Android is on it's way to suspend when stopServicePublish() is called, we need to call nsd.unregisterService() synchronously + // to force it to run before the device goes to sleep. If instead it is scheduled to run in the Android thread, it will not run + // until the device is woken back up. + if (qGuiApp->applicationState() == Qt::ApplicationSuspended) { ref.callMethod("unregisterService"); - }); + } else { + QtAndroid::runOnAndroidThread([ref]() { + ref.callMethod("unregisterService"); + }); + } } void QZeroConfPrivate::startBrowser(QString type, QAbstractSocket::NetworkLayerProtocol protocol)