My notification has an action for which an event occurs inside the application, I want to open the application if the application is minimized. I tried to do this, but it doesn't work for some reason, and sometimes the application crashes :(
action:
val answerIntent = Intent(context, ActionReceiver::class.java).apply {
action = "ACTION_ANSWER"
}
val answerPendingIntent: PendingIntent = PendingIntent.getBroadcast(context, acceptPendingId, answerIntent, 0)
Receiver
"ACTION_ANSWER" -> {
if (!singleton.isAppInForeground(context)) {
val openAppIntent = Intent(context, MainActivity::class.java)
context.startActivity(openAppIntent)
}
...any code
}
isAppInForeground
fun isAppInForeground(context: Context): Boolean {
val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
val runningAppProcesses = activityManager.runningAppProcesses ?: return false
for (processInfo in runningAppProcesses) {
if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
if (processInfo.processName == context.packageName) {
return true
}
}
}
return false
}
As per the Android documentation:
To improve app performance and UX, apps that target Android 12 or higher can't start activities from services or broadcast receivers that are used as notification trampolines.
This means that you cannot call startActivity()
from the BroadcastReceiver
that was invoked from the notification action. Doing so would result in an AndroidRuntmeException
.
You can, however make the notification action directly launch the Activity
instead of the BroadcastReceiver
. To perform some additional actions you would have to do it within the launched Activity
- you can achieve this by e.g. providing an Intent
with information about the origin of the launch. In this case consider using onNewIntent.