Возникли проблемы при использовании MessagingCenter для отправки сообщения из Android MainActivity для просмотра класса модели, не входящего в Android проект - PullRequest
0 голосов
/ 18 апреля 2020

Я попытался следовать найденным инструкциям здесь , чтобы добавить действие подписки на MessagingCenter при нажатии на уведомление, которое откроет конкретное представление c. Где-то мои Send / Subscribe не общаются друг с другом, и я просто не вижу, где. Подробная информация о Центре обмена сообщениями для меня все еще нова, поэтому я уверен, что где-то использовал не тот класс или отправителя.

С тех пор приведенный ниже код был изменен по сравнению с тем, что было показано мне в ссылке. Идея все еще примерно та же.

Вот метод SendLocalNotification в моем FirebaseService классе:

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());
    }

Вот OnNewIntent метод в android MainActivity :

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
        });
    }

1 Ответ

2 голосов
/ 18 апреля 2020

Для работы MessagingCenter необходимо использовать один и тот же тип / объект для отправителя и подписчика.

Поскольку вы отправляете из проекта Android, значение this Вы используете здесь:

MessagingCenter.Send(this, "Notification");

представляет MainActivity.

И когда вы подписываетесь в своей ViewModel, вы используете объект ViewModel

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

Это причина, по которой вы не получаете сообщение на другой стороне.

Чтобы оно работало, вам необходимо изменить следующее:

В основном действии Android используйте Xamarin.Forms .Application Class:

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 .

Надеюсь, это поможет .-

...