Xamarin - null reference exception while trying to

2019-07-09 06:45发布

Both trying to display a toast and to start a new activity fail. There HAS to be a way to make this work. Is there a way to notify the UI about something happening, an event or something?

Right now I am only able to log the info about the messages to console output.

The context itself is not null, but something else, possibly related to it, is causing the null reference exception.

Here's my code:

[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");

        // this fails
        Toast.MakeText(this, msg, ToastLength.Long).Show();

        // this fails too
        Intent pa = new Intent(this, typeof(PopupActivity));
        pa.AddFlags(ActivityFlags.NewTask);
        StartActivity(pa);
    }


}

2条回答
forever°为你锁心
2楼-- · 2019-07-09 07:29

This is a context Error. This is null therefore you get a null exception pointer. It is null because it is inside a service and not an activity.

You should try to use Application.Context instead of this. It is a static in Xamarin.Droid and should return the context.

(Note that I can't test is atm)

查看更多
我想做一个坏孩纸
3楼-- · 2019-07-09 07:34

I resolved this issue with Xamarin.Forms and MessagingCenter.

Here's my service:

[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");

        // send a string via Xamarin MessagingCenter
        MessagingCenter.Send<object, string>(this, "ShowAlert", msg);
    }
}

And here's part of my PCL App class constructor:

// subscribe to the messages
MessagingCenter.Subscribe<object, string>(this, "ShowAlert", (s, msg) =>
{
    // run on UI thread
    Device.BeginInvokeOnMainThread(() =>
    {
        MainPage.DisplayAlert("Push message", msg, "OK");
    });
});
查看更多
登录 后发表回答