I used Xamarin Form. 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. It is my code for notification:
public void Show(string title, string body, int id, DateTime notifyTime)
{
var intent = CreateIntent(id);
var localNotification = new LocalNotification();
localNotification.Title = title;
localNotification.Body = body;
localNotification.Id = id;
localNotification.NotifyTime = notifyTime;
if (NotificationIconId != 0)
{
localNotification.IconId = NotificationIconId;
}
else
{
localNotification.IconId = Resource.Drawable.Icon24;
}
var serializedNotification = SerializeNotification(localNotification);
intent.PutExtra(ScheduledAlarmHandler.LocalNotificationKey, serializedNotification);
var pendingIntent = PendingIntent.GetBroadcast(Application.Context, 0, intent, PendingIntentFlags.CancelCurrent);
var triggerTime = NotifyTimeInMilliseconds(localNotification.NotifyTime);
var alarmManager = GetAlarmManager();
alarmManager.Set(AlarmType.RtcWakeup, triggerTime, pendingIntent);
}
It is code in ScheduledAlarmHandler:
[BroadcastReceiver(Enabled = true)]
public class ScheduledAlarmHandler : BroadcastReceiver
{
...........
public override void OnReceive(Context context, Intent intent)
{
var extra = intent.GetStringExtra(LocalNotificationKey);
var notification = DeserializeNotification(extra);
var builder = new NotificationCompat.Builder(Application.Context)
.SetContentTitle(notification.Title)
.SetContentText(notification.Body)
.SetSmallIcon(notification.IconId)
.SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Notification))
.SetAutoCancel(true);
var resultIntent = LocalNotificationsService.GetLauncherActivity();
resultIntent.SetFlags(ActivityFlags.NewTask | ActivityFlags.ClearTask);
var stackBuilder = Android.Support.V4.App.TaskStackBuilder.Create(Application.Context);
stackBuilder.AddNextIntent(resultIntent);
var resultPendingIntent =
stackBuilder.GetPendingIntent(0, (int)PendingIntentFlags.UpdateCurrent);
builder.SetContentIntent(resultPendingIntent);
var notificationManager = NotificationManagerCompat.From(Application.Context);
notificationManager.Notify(notification.Id, builder.Build());
}
....
}
This is atribute for my MainActivity
[Activity (Icon = "@drawable/icon",
ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation, LaunchMode.SingleTop)]