Xamarin - is there a way to notify Xamarin.Forms from a native project?

◇◆丶佛笑我妖孽 提交于 2020-01-02 05:20:09

问题


So, I have this code in my native project (Android MainActivity OnCreate), which doesn't do anything:

var container = TinyIoCContainer.Current;
TinyMessengerHub tmh = (TinyMessengerHub)container.Resolve<ITinyMessengerHub>();

tmh.Subscribe<LocalMessage>((m) => {
    // this doesn't show
    Toast.MakeText(this, m.Content, ToastLength.Long);
});

Here's where I notify the app using TinyMessenger:

[Service(Exported = false), IntentFilter(new[] { "com.google.android.c2dm.intent.RECEIVE" })]
class MyGcmListenerService : GcmListenerService
{
    public override void OnMessageReceived(string from, Bundle data)
    {
        string msg = data.GetString("message");

        var container = TinyIoCContainer.Current;
        TinyMessengerHub tmh = (TinyMessengerHub)container.Resolve<ITinyMessengerHub>();
        tmh.Publish(new LocalMessage(this, msg));
    }
}

I tried to add TinyMessenger to my PCL, but apparently it was not supported (there were missing references in the TinyIoc.cs file etc., the same code runs well in the Android project)

So, is there any way to inform Xamarin.Forms about an arriving message so that I could e.g. display an alert window?


回答1:


This example is done with a Page, but you can subscribe/unsubscribe with your Application class, or selectively within your app logic.

In your Xamarin.Forms project subscribe/unsubscribe to a message via MessageCenter:

protected override void OnAppearing()
{
    base.OnAppearing();
    MessagingCenter.Subscribe<object, string>(this, "ShowAlertMessage", (sender, msg) =>
    {
        Device.BeginInvokeOnMainThread(() => {
            MainPage.DisplayAlert("Push message", msg, "OK"); 
        });
    });
}

protected override void OnDisappearing()
{
    base.OnDisappearing();
    MessagingCenter.Unsubscribe<object>(this, "ShowAlertMessage");
}

In "native" project send message via MessageCenter:

MessagingCenter.Send<object, string> (this, "ShowAlertMessage", "StackOverFlow Rocks");


来源:https://stackoverflow.com/questions/37621140/xamarin-is-there-a-way-to-notify-xamarin-forms-from-a-native-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!