Search code examples
c#xamarin.formsxamarin.androidmessagingcenter

MessageCenter subscription method does not happen


I've never worked with Message Center before and probably make some ridiculous errors when passing messages between apps. I try send message from Xamarin.Android to Xamarin.Forms.

Xamarin.Android project code:

MessagingCenter.Send(Xamarin.Forms.Application.Current, "MessageReceived", "new message");

Xamarin.Forms:

public partial class App : Application
{

    public App()
    {

        InitializeComponent();

        MainPage = (new MasterDetailPage()
        {
            Master = new MenuPage { Title = "Title" },
            Detail = new NavigationPage(new XxmsApp.MainPage()) { BarBackgroundColor = Color.Black }
        });

        MessagingCenter.Subscribe<App>(
            this,                                                     
            "MessageReceived",        
            (sender) => 
            {
                var StartPage = (((MainPage as MasterDetailPage).Detail as NavigationPage).RootPage as XxmsApp.MainPage);

                StartPage.DisplayAlert(
                    "message",
                    "message received",
                    "ok");
            });    
    }

    // ...

}

But method specified as third argument for Subscribe<App> is never called. I also tried this:

        Device.BeginInvokeOnMainThread(() =>
        {
            MessagingCenter.Send(Xamarin.Forms.Application.Current, "MessageReceived", "new message");
        });

But nothing.

What am I doing wrong?


Solution

  • In your android project code

    MessagingCenter.Send<object, object>(this, "MessageReceived", "new message");
    

    in your shared code

     MessagingCenter.Subscribe<object, object>(this, "MessageReceived", (sender, args) =>
        {
    
    var StartPage = (((MainPage as MasterDetailPage).Detail as NavigationPage).RootPage as XxmsApp.MainPage);
    
                    StartPage.DisplayAlert(
                        "message",
                        "message received",
                        "ok");
        });