簡體   English   中英

無法使用 MessagingCenter 從 Android MainActivity 發送消息以查看 model class 不在 ZE84E30B9390CDB6DZDB8 項目中

[英]Having trouble using MessagingCenter to send a message from Android MainActivity to view model class not in Android project

我嘗試按照此處找到的說明在將打開特定視圖的通知點擊上添加 MessagingCenter 訂閱操作。 在某個地方我的發送/訂閱沒有互相交談,我只是看不到在哪里。 消息中心的細節對我來說仍然是新的,所以我確定我只是在某處使用了錯誤的 class 或發件人。

下面的代碼已根據鏈接中顯示的內容進行了修改。 這個想法仍然大致相同。

這是我的FirebaseService class 中的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
        });
    }

要使MessagingCenter正常工作,您需要在發送者和訂閱者上使用相同的類型/對象。

由於您是從 Android 項目發送的,因此您在此處使用的this值:

MessagingCenter.Send(this, "Notification");

表示 MainActivity。

當您訂閱 ViewModel 時,您使用的是 ViewModel object

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

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

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

在Android主Activity中,使用Xamarin.Forms.Application Z9BD81329FEBF6EFE22788E03

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

並在您的 ViewModel 中使用相同的 Xamarin.Forms.Application class 和 ZA8CFDE6331BD4B62AC96F8911

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

這樣,您將符合MessagagingCenter的預期。

希望這可以幫助。-

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM