Resolve Android.Views.WindowsManagerBadTokenException exception

I am currently developing an application using Xamarin.Forms that will be available on the Android and iOS platforms. When the application is first loaded on device, I check to see if there is an internet connection available on the device. I want to display a dialog box if an internet connection is not available.

Here is the following snippet of code I am using to check the internet on the Xamarin.Forms.ContentPage

    App.Notification.DisplayLocalNotifications("No Internet", "You need an internet connection to access certain application content");

I am using dependency injection to build the appropriate module for handling dialog boxes for each appropriate environment. The Android is throwing the following exception

Android.Views.WindowManagerBadTokenException: Unable to add window -- token null is not for an application

Here is the code for the DisplayLocalNotification method on the Android:

public void DisplayLocalNotification(string title, string content)
     AlertDialog.Builder builder = new AlertDialog.Builder(Application.Context)
          .SetPositiveButton("OK", (EventHandler<DialogClickEventArgs>) null);

      AlertDialog alert = builder.Create();

      var okBtn = alert.GetButton((int)DialogButtonType.Positive);

      okBtn.Click += (sender, args) =>

After doing some research, I need to get pass the current activity to the AlertDialog.Builder constructor instead of the Application.Context. How do I get the current activity object from the applicatio context when you need to the activity outside of the activity context?


  • DanielGPDanielGP COMember ✭✭

    @MichaelKniskern thank you very much! it worked!

  • qweerqweer Member ✭✭

    I've got error

    Android.Views.WindowManagerBadTokenException: Unable to add window -- token null is not valid; is your activity         
    running? xamarin

    You save my time. Thank you @MichaelKniskern !

  • Oracle22Oracle22 USMember ✭✭
    edited April 26

    Resolve my problem to change Application.Context => Forms.Context
    Thanks #MichaelKniskern

Sign In or Register to comment.