I have an application with notifications that open a certain activity if I click them. I want that, if I click the notification and the activity is already opened, it's not started again, but just brought to front.
I thought I could do it with the flag FLAG_ACTIVITY_BROUGHT_TO_FRONT
or FLAG_ACTIVITY_REORDER_TO_FRONT
, but it keeps opening it again so I have the activity twice.
This is my code:
event_notification = new Notification(R.drawable.icon,
mContext.getString(R.string.event_notif_message), System.currentTimeMillis());
Intent notificationIntent = new Intent(mContext, EventListActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
sendNotification(event_notification, notificationIntent, mContext.getString(R.string.event_notif_title),
body, Utils.PA_NOTIFICATIONS_ID);
Can I manage it with flags or should I store a variable in SharedPreferences to check if it's opened or not?
Thanks!
Just Copy the code and paste it in your main launcher activity.
Here is Original Answer
Use
onNewIntent()
for handling new data from notification click and refresh the activity.In
onNewIntent
get the new data from the new intent(which served by the new notification) and catch them, for example:title = intent.getStringExtra("title")
in
onCreate
previously :)It will refresh present activity with new notification data.
You can also follow this tutorial: http://androidrace.com/2016/12/10/how-to-refresh-activity-on-new-notification-click-android-developer/
Try setting the flags to
Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP
instead.From the documentation for FLAG_ACTIVITY_CLEAR_TOP (emphasis mine):
You need to set the
launchMode
attribute of theActivity
you are starting tosingleTop
. This will cause incoming Intents to be delivered to the existing instance rather than starting a new instance when thatActivity
is already at the top of the task's stack.This is done in the manifest by adding
android:launchMode="singleTop"
to the<activity>
element. To access the latest Intent (if you are interested in any data that may have passed in with it), overrideonNewIntent()
in yourActivity
.I think you should add some logic to make it work, maybe this can help:
For example I have a Splash Screen (Launcher and MAIN) of APP:
And in my FirebaseService I have done the following: