0

我尝试按照此处找到的说明在将打开特定视图的通知点击上添加 MessagingCenter 订阅操作。在某个地方我的发送/订阅没有互相交谈,我只是看不到在哪里。消息中心的细节对我来说仍然是新的,所以我确定我只是在某个地方使用了错误的类或发件人。

下面的代码已根据链接中显示的内容进行了修改。这个想法仍然大致相同。

这是我的FirebaseService类中的SendLocalNotification方法:

void SendLocalNotification(string body)
    {
        var intent = new Intent(this, typeof(MainActivity));
        intent.AddFlags(ActivityFlags.SingleTop);
        intent.PutExtra("OpenPage", "SomePage");

        //Unique request code to avoid PendingIntent collision.
        var requestCode = new Random().Next();
        var pendingIntent = PendingIntent.GetActivity(this, requestCode, intent, PendingIntentFlags.OneShot);

        var notificationBuilder = new NotificationCompat.Builder(this)
            .SetContentTitle("Load Match")
            .SetSmallIcon(Resource.Drawable.laundry_basket_icon_15875)
            .SetContentText(body)
            .SetAutoCancel(true)
            .SetShowWhen(false)
            .SetContentIntent(pendingIntent);

        if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
        {
            notificationBuilder.SetChannelId(AppConstants.NotificationChannelName);
        }

        var notificationManager = NotificationManager.FromContext(this);
        notificationManager.Notify(0, notificationBuilder.Build());
    }

这是android MainActivity中的OnNewIntent方法:

protected override void OnNewIntent(Intent intent)
    {
        if (intent.HasExtra("OpenPage"))
        {
            MessagingCenter.Send(this, "Notification");
        }

        base.OnNewIntent(intent);
    }

这里是我尝试在我的LoadsPageViewModel中订阅消息的地方(不在 android 项目中):

public LoadsPageViewModel()
    {
        MessagingCenter.Subscribe<LoadsPageViewModel>(this, "Notification", (sender) =>
        {
             // navigate to a view here
        });
    }
4

1 回答 1

8

为了MessagingCenter工作,您需要在发送者和订阅者上使用相同的类型/对象。

由于您是从 Android 项目发送的,因此this您在此处使用的值:

MessagingCenter.Send(this, "Notification");

表示 MainActivity。

当您订阅 ViewModel 时,您正在使用 ViewModel 对象

MessagingCenter.Subscribe<LoadsPageViewModel>(this, "Notification", (sender) => { });

这就是您在另一端没有收到消息的原因。

要使其正常工作,您需要更改以下内容:

在 Android Main Activity 中,使用 Xamarin.Forms.Application 类:

MessagingCenter.Send(Xamarin.Forms.Application.Current, "Notification");

并在您的 ViewModel 中使用相同的 Xamarin.Forms.Application 类和对象:

MessagingCenter.Subscribe<Xamarin.Forms.Application>(Xamarin.Forms.Application.Current, "Notification", (sender) =>
{
    Console.WriteLine("Received Notification...");
});

这样,您将遵守MessagagingCenter预期。

希望这可以帮助。-

于 2020-04-18T04:47:11.120 回答