I start a service within a place in the app and create a notification from there. I put the app to the background and click the notification
What I want to happen: The app goes to the foreground in the same state it was in, just as if I had pressed the 'view all background apps' button on the device and selected it.
What actually happens: I go to the main screen of the app.
I have combed through a bunch of threads and tried different things. Every time I change anything, the app simply does not open when I press the notification.
class TestService : Service() {
private lateinit var notificationBuilder: NotificationCompat.Builder
...
private fun createNotification(): Notification {
...
notificationBuilder = NotificationCompat.Builder(this, channelId)
notificationBuilder
.setSmallIcon(R.drawable.ic_notif)
.setContentTitle(titleText)
.setContentText(getFormattedTime())
.setOnlyAlertOnce(true)
.setContentIntent(PendingIntent.getActivity(this, 1, Intent(this, MainActivity::class.java), PendingIntent.FLAG_IMMUTABLE))
.setOngoing(true)
...
return notificationBuilder.build()
}
You just need to use a launch Intent
instead, like this:
val intent = getPackageManager().
getLaunchIntentForPackage("my.package.name")
and then
.setContentIntent(PendingIntent.getActivity(this, 1, intent, PendingIntent.FLAG_IMMUTABLE))
A launch Intent
has some additional flags set, that cause the task to simply be brought to the foreground (if it is already running). This has the same effect as when the user taps the app icon from the HOME screen.