Xamarin Forms:点击推送通知时加载内容页 android

Xamarin Forms: Load a contentpage when tap push notification android

我已完成接收来自 FCM 控制台的测试通知。现在我试图在点击通知时打开一个页面。关于如何实现这一目标的任何想法?我在互联网上进行了搜索,但找不到可行的解决方案。我也可以通过邮递员发送通知。

我不知道您的实际 Firebase 实现是什么,但这可能对您有所帮助。

Xamarin Forms 中有一个很好的 Firebase 包,我们在 CrossGeeks 团队制作的生产应用程序中使用了它。它运行良好,handlers 满足您的所有需求。这适用于 iOS 和 Android,您不需要编写特定于平台的代码,只需在 AppDelegate.csMainActivity.cs

中编写配置和一些代码

https://github.com/CrossGeeks/FirebasePushNotificationPlugin/blob/master/docs/FirebaseNotifications.md#notification-events

我写了一个简单的 PushNotificationService 处理自动刷新 and/or 考虑推送通知数据推送新页面。

当应用关闭并且用户点击通知时,我使用 Akavache 存储推送通知数据。

 CrossFirebasePushNotification.Current.OnNotificationOpened += async (s, p) =>
            {
                if (App.AppBeenResumed)
                {
                    await BlobCache.UserAccount.InsertObject("pushNotifData", p.Data);
                }
                else
                {
                    await ProcessReceivedPushNotification(p.Data);
                }
            }; 

然后在应用程序的着陆页上,我检查页面的 OnAppearing 方法中是否存在现有的推送通知数据。

protected override void OnAppearing()
        {
            base.OnAppearing();
            App.AppBeenResumed = false;
            HandlePushNotificationIfExists();
        }

 private async void HandlePushNotificationIfExists()
        {
            IDictionary<string, object> pushNotifData;
            try
            {
                pushNotifData = await BlobCache.UserAccount.GetObject<IDictionary<string, object>>("pushNotifData");
            }
            catch (KeyNotFoundException)
            {
                pushNotifData = null;
            }

            if (pushNotifData == null) return;
            await BlobCache.UserAccount.InvalidateAllObjects<IDictionary<string, object>>();
            await PushNotificationService.ProcessReceivedPushNotification(pushNotifData);
        }

ProcessReceivedPushNotification 中,您可以做任何您想做的事情...直接推送页面或其他...调用另一个服务来完成推送新页面和一些业务流程的工作。

注意 App.AppBeenResumed是一个static bool,判断App是否已经启动或恢复正确处理push notif的处理过程(process it instant或将其存储在 blobcache 中,以便稍后在登录页面出现时对其进行处理)。

MainActivity.cs 中:

 protected override void OnCreate(Bundle bundle)

        {
           ...
           LoadApplication(new App(true));
        }

App.cs 中:

 public App(bool beenResumedOrStarted)
        {
            ...
            AppBeenResumed = beenResumedOrStarted;
            ...
        }

    protected override void OnResume()
    {
        AppBeenResumed = false;
    }


    protected override void OnSleep()
    {
        //iOS states are not the same so always false when device is iOS
        AppBeenResumed = Device.RuntimePlatform != Device.iOS;
    }

我按以下方式处理通知点击。页面加载在 App.xaml.cs.

中处理

在 OnCreate() 上:

//Background or killed mode
if (Intent.Extras != null)
{
    foreach (var key in Intent.Extras.KeySet())
    {
        var value = Intent.Extras.GetString(key);
        if (key == "webContentList") 
        {
            if (value?.Length > 0)
            {
                isNotification = true;
                LoadApplication(new App(domainname, value));
            }
        }
    }
}
//Foreground mode
if (FirebaseNotificationService.webContentList.ToString() != "")
{
    isNotification = true;
    LoadApplication(new App(domainname, FirebaseNotificationService.webContentList.ToString()));
    FirebaseNotificationService.webContentList = "";
}

//Normal loading
if (!isNotification)
{
    LoadApplication(new App(domainname, string.Empty));
}

在 FirebaseNotificationService 上:

[Service]
[IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })]
public class FirebaseNotificationService : FirebaseMessagingService
{
    public static string webContentList = "";
    public override void OnMessageReceived(RemoteMessage message)
    {
        base.OnMessageReceived(message);
        webContentList = message.Data["webContentList"];

        try
        {
            SendNotificatios(message.GetNotification().Body, message.GetNotification().Title);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error:>>" + ex);
        }
    }

    public void SendNotificatios(string body, string Header)
    {
        if (Build.VERSION.SdkInt < BuildVersionCodes.O)
        {
            var intent = new Intent(this, typeof(MainActivity));
            intent.AddFlags(ActivityFlags.ClearTop);
            var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot);

            var notificationBuilder = new Android.App.Notification.Builder(this, Utils.CHANNEL_ID)
                        .SetContentTitle(Header)
                        .SetSmallIcon(Resource.Drawable.icon)
                        .SetContentText(body)
                        .SetAutoCancel(true)
                        .SetContentIntent(pendingIntent);

            var notificationManager = NotificationManager.FromContext(this);

            notificationManager.Notify(0, notificationBuilder.Build());
        }
        else
        {
            var intent = new Intent(this, typeof(MainActivity));
            intent.AddFlags(ActivityFlags.ClearTop);
            var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot);

            var notificationBuilder = new Android.App.Notification.Builder(this, Utils.CHANNEL_ID)
                        .SetContentTitle(Header)
                        .SetSmallIcon(Resource.Drawable.icon)
                        .SetContentText(body)
                        .SetAutoCancel(true)
                        .SetContentIntent(pendingIntent)
                        .SetChannelId(Utils.CHANNEL_ID);

            if (Build.VERSION.SdkInt < BuildVersionCodes.O)
            {
                return;
            }

            var channel = new NotificationChannel(Utils.CHANNEL_ID, "FCM Notifications", NotificationImportance.High)
            {
                Description = "Firebase Cloud Messages appear in this channel"
            };

            var notificationManager = (NotificationManager)GetSystemService(NotificationService);
            notificationManager.CreateNotificationChannel(channel);

            notificationManager.Notify(0, notificationBuilder.Build());
        }
    }