Opening message/dialog box globally

Hello,

I need to display some kind of message when the internet connection state changes. So no matter in which activity user currently is I need to display message saying that the connection is missing and prevent him from continue working without internet connection.

So I have the BroadcastReceiver in my MainActivity which fires an event when the connection state is changed.
I was thinking about two solutions:
1. Fire the Alert Dialog from the main activity. The problem is that I have to pass the Context for new AlertDialog.Builder(this); and it must be the current activity. I tried passing ApplicationContextinstead of this but then I getAndroid.Views.WindowManagerBadTokenException: Unable to add window -- token null is not for an application
2. Another solution is to create AlertActivity with Dialog style @android:style/Theme.Holo.Light.Dialog.NoActionBar. But in this case I need to be able to close that activity from MainActivity. Of course it's possible to add another BroadcastReceiver in that AlertActivity and close it from there, but it wouldn't be the best practice.

Any ideas what would be the best way of solving this? Thanks.

Posts

  • tefotazotefotazo ARMember

    You can make an extension method like this:
    public static class UIHelpers
    {
    public static void ShowAlert(this Activity activity, string title, string message)
    {
    new AlertDialog.Builder (activity).SetTitle (title).SetMessage (message).SetPositiveButton (activity.GetString (Resource.String.Accept), (s2, e2) => { }).Show ();
    }
    }

  • LjusnanLjusnan DEMember ✭✭✭

    Don't forget to run this on the UI thread.

    Like this:
    activity.RunOnUiThread(() =>
    {
    new AlertDialog.Builder (activity).Show();
    }

Sign In or Register to comment.