From 95fa61a65e157ebc440e147f055349f743449f3c Mon Sep 17 00:00:00 2001 From: mendhak Date: Sun, 26 May 2024 22:13:59 +0100 Subject: [PATCH] Stabilize the app when permissions have been revoked. Moved the start service to only after the permission check is complete. In the stop service, only stop the service if notifications are enabled, due to a weird scenario where the service might start and immediately end due to lack of notifications, resulting in an app crash. How did we end up like this. Issue #1138 Issue #1053 --- gpslogger/src/main/AndroidManifest.xml | 2 ++ .../mendhak/gpslogger/GpsMainActivity.java | 26 ++++++++++++++++--- 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/gpslogger/src/main/AndroidManifest.xml b/gpslogger/src/main/AndroidManifest.xml index a189a366e..bcf749f78 100644 --- a/gpslogger/src/main/AndroidManifest.xml +++ b/gpslogger/src/main/AndroidManifest.xml @@ -27,6 +27,8 @@ + + = Build.VERSION_CODES.TIRAMISU) { + permissions.add(Manifest.permission.POST_NOTIFICATIONS); + } if (Build.VERSION.SDK_INT == Build.VERSION_CODES.Q) { // Only on Android 10 (Q), the permission dialog can include an 'Allow all the time' @@ -1501,6 +1507,16 @@ private void startAndBindService() { * Stops the service if it isn't logging. Also unbinds. */ private void stopAndUnbindServiceIfRequired() { + if(!NotificationManagerCompat.from(this).areNotificationsEnabled()) { + // Alright. Why is this needed. + // If the notification permission has been revoked or not granted for whatever reason. + // When the application opens, the service starts, then stops right away. + // Android requires a notification to be shown for a foreground service within 5 seconds. + // So the application crashes and comes back repeatedly. Very weird. + // The answer - if notifications are disabled, don't unbind the service. It will stop on its own. + // Might be related: https://stackoverflow.com/questions/73067939/start-foreground-service-after-notification-permission-was-disabled-causes-crash + return; + } if (session.isBoundToService()) { try { @@ -1514,6 +1530,10 @@ private void stopAndUnbindServiceIfRequired() { if (!session.isStarted()) { LOG.debug("Stopping the service"); try { + // Stop service crashes if the intent is null. lol + if(serviceIntent == null){ + serviceIntent = new Intent(this, GpsLoggingService.class); + } stopService(serviceIntent); } catch (Exception e) { LOG.error("Could not stop the service", e);