簡體   English   中英

Xamarin Android 應用程序上下文為空

[英]Xamarin Android application context is null

正如我在標題中所說,這是我的問題。 為什么我無法訪問班級中的上下文? 有什么辦法可以在這個類中獲得上下文的實例嗎?

[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();
    }
}

您沒有可用的 Activity 上下文的原因是它位於服務中,並且沒有與之關聯的 UI。

如果你真的想顯示一個對話框,你有兩個選擇:

使用基於系統的警報:

var dialog = new AlertDialog.Builder(this).Create();
dialog.Window.SetType(Android.Views.WindowManagerTypes.SystemAlert);
dialog.SetTitle("Push message");
dialog.SetMessage(message);
dialog.SetButton("OK", (sender, e) => { });
dialog.Show();

注意:這種類型的警報顯示在一切之上,因此需要您添加清單權限。

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />

另一種方法是創建一個新的Activity子類,並在其OnCreate創建您的AlertDialog並將this用作您的上下文,因為它將是一個 Activity。 然后,當您希望GcmListenerService顯示消息時,請創建此Activity的實例。

使用Forms.Context代替Application.Context

我使用 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);
    }
}

這是我的 PCL App 類構造函數的一部分:

// subscribe to the messages
MessagingCenter.Subscribe<object, string>(this, "ShowAlert", (s, msg) =>
{
    // run on UI thread
    Device.BeginInvokeOnMainThread(() =>
    {
        MainPage.DisplayAlert("Push message", msg, "OK");
    });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM