Martin Dusek
Martin Dusek

Reputation: 1292

Foreground service start once and display activity on click

I have 5 activities in my app. Every activity starts the same foreground service.

In onStartCommand method of the service foreground notification is created which unfortunately means that every call of startForegroundService() in any activity plays notification sound (even though the service is already running). How can I create the foreground notification only once or at least how not to play notification sound on successive startForegroundService() calls?

The other related question is: how can I go back to my application when I click the foreground notification? I have 5 activites and I would like to reopen the activity that was the last one the user was interacting with.

Upvotes: 3

Views: 2577

Answers (2)

lubilis
lubilis

Reputation: 4160

How can I create the foreground notification only once or at least how not to play notification sound on successive startForegroundService() calls?

You can check if the notification is already visible and show it only if it's not visible. You need to have a reference to the notification PendingIntent and notificationId.

fun isNotificationVisible(context: Context, notificationIntent: Intent, notificationId: Int): Boolean {
    return PendingIntent.getActivity(context, notificationId, notificationIntent, PendingIntent.FLAG_NO_CREATE) != null
}

how can I go back to my application when I click the foreground notification?

You need a PendingIntent to open the app from a notification. To open the last activity shown you can remember this using Preferences in the onResume() method of each activity and route the notification into a routing activity that starts the right activity according to the value saved into the preferences.

val intent = Intent(context, RouteActivity::class.java)
val notificationBuilder = NotificationCompat.Builder(context, channelId)
    .setContentIntent(intent)
val notificationManager = NotificationManagerCompat.from(context)
val notification = notificationBuilder.build()
notificationManager.notify(notificationId, notification)

Another way to do this is to update the notification PendingIntent if it's already visible with the last activity shown. In this case you don't have to store any value on Preferences and you don't need a route activity.

Upvotes: -1

towhid
towhid

Reputation: 3278

#1. before starting the service just check if its already running or not. In that case this will help you https://stackoverflow.com/a/5921190/6413387

#2. To reopen your last opened activity, you need to update the pending intent of your notification. Hope you will find your answer here https://stackoverflow.com/a/20142620/6413387

Upvotes: 1

Related Questions