C# Xamarin-尝试显示toast或从服务启动活动时出现空引用异常
尝试显示祝酒词和启动新活动都失败。一定有办法让这一切顺利进行。有没有一种方法可以将发生的事情、事件或其他事情通知UI 现在我只能将有关消息的信息记录到控制台输出 上下文本身不是空的,但可能与之相关的其他内容导致了空引用异常 这是我的密码:C# Xamarin-尝试显示toast或从服务启动活动时出现空引用异常,c#,service,xamarin,xamarin.android,C#,Service,Xamarin,Xamarin.android,尝试显示祝酒词和启动新活动都失败。一定有办法让这一切顺利进行。有没有一种方法可以将发生的事情、事件或其他事情通知UI 现在我只能将有关消息的信息记录到控制台输出 上下文本身不是空的,但可能与之相关的其他内容导致了空引用异常 这是我的密码: [Service(Exported = false), IntentFilter(new[] { "com.google.android.c2dm.intent.RECEIVE" })] class MyGcmListenerService : GcmList
[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);
}
}
这是一个上下文错误。这是null,因此您会得到一个null异常指针。它为null,因为它位于服务内部,而不是活动内部 您应该尝试使用
Application.Context
而不是this
。它在Xamarin.Droid中是静态的,应该返回上下文
(请注意,我无法测试的是atm)我用Xamarin.Forms和MessagingCenter解决了这个问题 这是我的服务:
[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);
}
}
[Service(Exported=false),IntentFilter(new[]{“com.google.android.c2dm.intent.RECEIVE”}]
类MyGcmListenerService:GcmListenerService
{
public override void OnMessageReceived(来自的字符串,捆绑数据)
{
string msg=data.GetString(“消息”);
//通过Xamarin MessagingCenter发送字符串
MessagingCenter.Send(此为“ShowAlert”,msg);
}
}
下面是我的PCL应用程序类构造函数的一部分:
// subscribe to the messages
MessagingCenter.Subscribe<object, string>(this, "ShowAlert", (s, msg) =>
{
// run on UI thread
Device.BeginInvokeOnMainThread(() =>
{
MainPage.DisplayAlert("Push message", msg, "OK");
});
});
//订阅消息
订阅(此“ShowAlert”,(s,msg)=>
{
//在UI线程上运行
Device.beginInvokeMainThread(()=>
{
MainPage.DisplayAlert(“推送消息”,消息,“OK”);
});
});
您在创建的toast上没有调用Show()-methode的可能重复项。因此很明显,它从未显示过。我最初有Show()方法,只是忘了在这里添加它。您也可以尝试在类的构造函数中作为变量传递上下文。然后用变量代替这个。如果仍然不工作,我的想法就快用完了