简体   繁体   中英

Android - open or restart app after clicking push notification using flag activities

I am using push notifications in Android. When I receive a push notification, I want to open the application if it is still running, else it should open a new instance of it.

I am using

PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 
    Intent.FLAG_ACTIVITY_CLEAR_TOP | 
    Intent.FLAG_ACTIVITY_SINGLE_TOP | 
    Intent.FLAG_ACTIVITY_NEW_TASK);

But when I receive a push notification now and I click on it, nothing happens.

How can I still achieve this by using flagIntents?

You need to set the Intent flags on the Intent . You were specifying them in the call to get a PendingIntent . Try this:

notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | 
    Intent.FLAG_ACTIVITY_SINGLE_TOP | 
    Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
    notificationIntent, 0);

set following things in your Android Mainfest file

android:noHistory="true"
 android:launchMode = "singleTop"

In my case a running application restarted every time I clicked a push notification. But I don't want to restart the application.

In PendingIntent I have an intent for needed Activity1 that called Activity2. A bug was in these lines:

val intent = Intent(context, Activity2::class.java)
// Remove this line:
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
context.startActivity(intent)

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