Xamarin - 空引用异常,而试图显示一个烤面包或从服务开始活动 [英] Xamarin - null reference exception while trying to display a toast or start an activity from a service
问题描述
都试图展示敬酒,并开始新的活动失败。必须有一种方法,使这项工作。有没有一种方法来通知有关的东西发生,事件或事物的UI?
现在我只能记录有关消息的信息,以控制台输出。
上下文本身不为空,但别的东西,可能与它,导致了空引用异常。
下面是我的代码:
[服务(出口= FALSE),IntentFilter的(新[] {com.google.android .c2dm.intent.RECEIVE})
类MyGcmListenerService:GcmListenerService
{
公共覆盖无效OnMessageReceived(字符串从,捆绑数据)
{
弦乐味精= data.GetString(消息);
//失败
Toast.MakeText(这一点,味精,ToastLength.Long).Show();
//失败过
意向PA =新意图(此的typeof(PopupActivity));
pa.AddFlags(ActivityFlags.NewTask);
StartActivity(PA);
}
}
我解决了与Xamarin.Forms和MessagingCenter这个问题。
下面是我的服务:
[服务(出口= FALSE),IntentFilter的(新[] {com.google.android.c2dm.intent.RECEIVE})
类MyGcmListenerService:GcmListenerService
{
公共覆盖无效OnMessageReceived(字符串从,捆绑数据)
{
弦乐味精= data.GetString(信息);
//通过Xamarin MessagingCenter $ B $发送一个是字符串b MessagingCenter.Send<对象,字符串>(这一点,ShowAlert,味精);
}
}
这是我的PCL App类的构造函数的一部分:
//订阅的消息
MessagingCenter.Subscribe<对象,字符串>(这一点,ShowAlert(S ,味精)=>
{
//在UI线程
Device.BeginInvokeOnMainThread运行(()=>
{
MainPage.DisplayAlert(推消息味精,OK);
});
});
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);
}
}
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");
});
});
这篇关于Xamarin - 空引用异常,而试图显示一个烤面包或从服务开始活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!