Xamarin Android 应用程序上下文为空 [英] Xamarin Android application context is null
本文介绍了Xamarin Android 应用程序上下文为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
正如我在标题中所说,这是我的问题.为什么我无法访问班级中的上下文?有什么办法可以在这个类中获取上下文的实例吗?
As I said in the heading, this is my problem. Why can't I access the context in my class? Is there any way I could get the instance of the context in this class?
[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");
// the app breaks here
ShowPopup(msg);
Log.Info("GcmLstnrService", "From: " + from);
Log.Info("GcmLstnrService", "Msg: " + msg);
}
private void ShowPopup(string message)
{
// the app breaks here
AlertDialog.Builder builder = new AlertDialog.Builder(Application.Context);
AlertDialog dialog = builder.Create();
dialog.SetTitle("Push message");
dialog.SetMessage(message);
dialog.SetButton("OK", (sender, e) => { });
dialog.Show();
}
}
推荐答案
我使用 Xamarin.Forms 和 MessagingCenter 解决了这个问题.
I resolved this issue with Xamarin.Forms and 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);
}
}
这是我的 PCL App 类构造函数的一部分:
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 Android 应用程序上下文为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文