Handle Android push notifications actions in Xamarin.Forms

假如想象 提交于 2019-12-22 11:26:08

问题


So I just implemented FCM in my Xamarin.Forms Android app with this guide. Everything works pretty well, the notifications arrive, they play a sound, have an icon etc. Then I wanted to add an action to my notification, it has to open a certain page in my app.

And thats were my problem comes in, Xamarin.Forms puts all Android content in a single Activity. Which means that opening a certain page causes the whole OnCreate of the MainActivity to load again (And the LoadApplication as well).

My Notification

var notificationIntent = new Intent(this, typeof(MainActivity));

notificationIntent.AddFlags(ActivityFlags.ClearTop | ActivityFlags.NewTask);
notificationIntent.PutExtras(intent.Extras);

var pendingIntent = PendingIntent.GetActivity(this, 0, notificationIntent, PendingIntentFlags.UpdateCurrent);

NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
    .SetSmallIcon(Resource.Drawable.icon)
    .SetStyle(new NotificationCompat.BigTextStyle().BigText(text))
    .SetContentIntent(pendingIntent)
    .SetAutoCancel(true)
    .SetPriority((int)NotificationPriority.Max)
    .SetVibrate(new long[] { 0, 250, 100, 250, 0 })
    .SetLights(Color.Red, 1, 250)
    .SetContentTitle("Eindexamen")
    .SetContentText(text);

FCM Payload

{"data":{"message":"Notification Hub test notification", "action":"open-exam", "exam-id":"F50FC23C-B4EE-E611-80C3-000D3A218F79"}}

So my question is, how to open a Xamarin.Forms page without reloading the entire app on Android?


回答1:


The fixed turned out to be rather easy.

Instead of using ActivityFlags.ClearTop and ActivityFlags.NewTask use ActivityFlags.SingleTop.

Then in your MainActivity.cs override the OnNewIntent method.

protected override void OnNewIntent(Intent intent)
{
    base.OnNewIntent(intent);

    ProcessPushNotification(intent);
}


来源:https://stackoverflow.com/questions/42174909/handle-android-push-notifications-actions-in-xamarin-forms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!