简体   繁体   中英

Getting Context from Background thread in Xamarin Android

In my application, I need to invoke an alert method from the background thread. I need to get the Context from the background thread. While getting the context I am getting the token null error. Here is my code

Handler h = new Handler();
        BackgroService.Event += () =>
        {
            Action myAction = () =>
            {
                Dialog dialog = new Dialog(Application.Context);
                Android.App.AlertDialog.Builder alert = new Android.App.AlertDialog.Builder(Application.Context, Resource.Style.AlertDialog);
                alert.SetTitle("");
                alert.SetMessage("MSG");
                alert.SetPositiveButton(GetString(Resource.String.ok), (senderAlert, args) =>
                {
                    //MyAction
                    dialog.Dismiss();
                });
                dialog = alert.Create();
                dialog.Window.SetType(Android.Views.WindowManagerTypes.ApplicationPanel);
                dialog.Show();


            };
            h.PostDelayed(myAction, 1000);
        };

I am using Application.Context and also this are not working. Does any one have any idea of doing this properly.

我找到一种解决方案,通过使用WindowManagerTypes作为Toa​​st从后台线程显示警报

dialog.Window.SetType(Android.Views.WindowManagerTypes.Toast);

From the background thread call

RunOnUiThread(() =>
{
    //show the alert here (you can use the keyword 'this')
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM