简体   繁体   中英

How to launch an activity from a notification into the foreground?

Goal: My goal is to launch an Android activity into the foreground when the user taps on a notification. If a task of the app is open, tapping on the notification closes the notification drawer, and the activity opens in the foreground, as expected.

Problem: If no task of the app is open, however, upon tapping on the notification, the notification drawer remains in the foreground, and the activity only opens in the background.

Question: How to tell Android to close the notification drawer and put the opened activity in the foreground, no matter if the app has opened tasks or not?

Code snippet:

val intent = Intent(context, SplashActivity::class.java)
intent.addFlags(
    Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP
)
val pendingIntent = PendingIntent.getActivity(context, 0, intent, 0)
NotificationCompat.Builder(context, channelId)
    .build(title, text, icon, pendingIntent)

You can do this by using a PendingIntent .

See how on Start an Activity from a Notification . Hope this helps.

If I am right you want to close notification drawer when your activity opens. So please add these two lines in your code when you are opening your activity from notification.

Intent x = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);

sendBroadcast(x);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM