Skip to content

Commit

Permalink
Merge pull request #597 from hannesa2/RemoveForegroundNotification
Browse files Browse the repository at this point in the history
Remove foreground notification when the service is started in foreground
  • Loading branch information
hannesa2 authored Apr 3, 2024
2 parents c6812e5 + 6bb63ec commit bd56ec6
Showing 1 changed file with 17 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,7 @@ class MqttService : Service(), MqttTraceHandler {

// callback id for making trace callbacks to the Activity needs to be set by the activity as appropriate
private var traceCallbackId: String? = null
private var isForegroundStarted = false

var isTraceEnabled = false

Expand Down Expand Up @@ -228,6 +229,7 @@ class MqttService : Service(), MqttTraceHandler {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val foregroundServiceNotification = intent?.getParcelableExtra<Notification>(MQTT_FOREGROUND_SERVICE_NOTIFICATION)
if (foregroundServiceNotification != null) {
isForegroundStarted = true
startForeground(
intent.getIntExtra(MQTT_FOREGROUND_SERVICE_NOTIFICATION_ID, 1),
foregroundServiceNotification
Expand Down Expand Up @@ -312,6 +314,19 @@ class MqttService : Service(), MqttTraceHandler {
client.close()
}

/**
* Stop service, removing the notification if needed
*/
private fun stopService() {
if (isForegroundStarted) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
stopForeground(Service.STOP_FOREGROUND_REMOVE)
else
stopForeground(true)
}
stopSelf()
}

/**
* Disconnect from the server
*
Expand All @@ -328,7 +343,7 @@ class MqttService : Service(), MqttTraceHandler {
// the activity has finished using us, so we can stop the service
// the activities are bound with BIND_AUTO_CREATE, so the service will
// remain around until the last activity disconnects
stopSelf()
stopService()
}

/**
Expand All @@ -347,7 +362,7 @@ class MqttService : Service(), MqttTraceHandler {
// the activity has finished using us, so we can stop the service
// the activities are bound with BIND_AUTO_CREATE, so the service will
// remain around until the last activity disconnects
stopSelf()
stopService()
}

/**
Expand Down

0 comments on commit bd56ec6

Please sign in to comment.