1

I have created a custom notifcation control using AlertDialog which will displays at the Top. It works fine for some devices like Samsung Galaxy S7,S8 where it is running with Android 7.0 OS. However It doesn't works on some mobile devices with same OS running.

It is throwing "Unable to add window -- token null is not valid; is your activity running?" in Show Method. Any help would be really appreciated. The below is the code snippit. The syntax is xamarin. However the logics are same as native android.

public class MyNotificationControl
{
    AlertDialog b;

    public MyNotificationControl(Android.Content.Context context)
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(Android.App.Application.Context);
        LayoutInflater inflater = (LayoutInflater)context.GetSystemService(Context.LayoutInflaterService);
        View dialogView = inflater.Inflate(Resource.Layout.mynotification_layout, null);
        builder.SetView(dialogView);
        b = builder.Create();
        b.Window.SetType(WindowManagerTypes.Toast);

        Window window = b.Window;
        window.SetFlags(WindowManagerFlags.NotTouchModal, WindowManagerFlags.NotTouchModal);
        window.ClearFlags(WindowManagerFlags.DimBehind);
        window.SetGravity(GravityFlags.Top);
        window.SetBackgroundDrawableResource(Android.Resource.Color.Transparent);
    }

    public void Show()
    {
        try
        {
            b.Show();
        }
        catch(Exception ex)
        {
            //Here is my exception occurs.  Unable to add window -- token null is not valid; is your activity running?
        }
    }
    public void Close()
    {
        b?.Dismiss();
    }
}
Anees Deen
  • 1,385
  • 2
  • 17
  • 31

3 Answers3

4
  1. Pass the current activity context instead Application context in AlertDialog.Builder().
  2. Set the AlertDialog type to WindowManagerTypes.ApplicationPanel intead of Toast
AlertDialog.Builder builder = new AlertDialog.Builder(context);//current activity.
b.Window.SetType(WindowManagerTypes.ApplicationPanel);
Anees Deen
  • 1,385
  • 2
  • 17
  • 31
2

Please refer to this.

This exception occurred while app was trying to notify user from the background thread by opening a Dialog.

Do like this:

RunOnUiThread(() => {
    if (!IsFinishing) {
        //to call the show method
    }
});

Or you can refer to this.

Robbit
  • 4,300
  • 1
  • 13
  • 29
1

for fragment just use

AlertDialog.Builder builder = new AlertDialog.Builder(this.getContext());
Nick
  • 138,499
  • 22
  • 57
  • 95
LizyLizy
  • 11
  • 1