In an app I'm making, if the app is minimized, using the code below I'll show a Notification using NotificationCompat.Builder
, and when I click on the notification, if user is outside of the app, the app opens.
My problem is that when the app opens, the onCreate
is called again which causes problems in the app, whereas if had opened the app by clicking on the icon in the launcher, onStart
and onwards would be called. So is there a way to prevent calling onCreate
?
I tried setting flags (Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP
) on the intent I use when creating PendingIntent object, but that didn't help.
public static void notificatePush(Context context, int
notificationId, String tickerText, String contentTitle, String
contentText, Intent intent) {
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(contentTitle)
.setContentText(contentText)
.setTicker(tickerText);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);//This didn't work
PendingIntent resultPendingIntent = PendingIntent.getActivity(context, notificationId, intent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
mBuilder.setAutoCancel(true);
mBuilder.setOnlyAlertOnce(true);
NotificationManager notifyMgr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notifyMgr.notify(notificationId, mBuilder.build());
}
Try setting the launch mode of your activity in the manifest to this
<activity
android:name=".MyActivity"
android:launchMode="singleTop" />
Explanation: New instance of singleTop
activity is not created every time. If the target task already has an existing instance, new instance will not be created of the activity, instead the already created instance will receive the calling intent.
Check out android documentation for launch modes, and use the one that is suitable for your use case.