2

I'm trying to create an overlay window but when I try to add the view to the WindowManager, it gives me an exception. I have added the "SYSTEM_ALERT_WINDOW" permission and I have enabled "Draw over other apps" in app info. I'm calling this from within the onCreate function of a service.

  • Device : Emulator running 8.0.0
  • Target SDK and Compiled SDK versions: 26
  • AppCompat version: 26.0.0

Code:

    WindowManager manager = (WindowManager)getSystemService(WINDOW_SERVICE);
    LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);

    RelativeLayout overlay = (RelativeLayout) inflater.inflate(R.layout.button_main, null);

    final WindowManager.LayoutParams params =
            new WindowManager.LayoutParams(
                    WindowManager.LayoutParams.MATCH_PARENT,
                    WindowManager.LayoutParams.WRAP_CONTENT,
                    WindowManager.LayoutParams.TYPE_APPLICATION_PANEL,
                    0,
                    PixelFormat.TRANSLUCENT);


    params.gravity = Gravity.TOP | Gravity.START;
    params.x = 0;
    params.y = 0;

    manager.addView(overlay, params);

Exception stacktrace:

Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?
    at android.view.ViewRootImpl.setView(ViewRootImpl.java:764
    at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:356)
    at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:92)

No matter what TYPE I use for the LayoutParams, I always get this crash.

azizbekian
  • 60,783
  • 13
  • 169
  • 249
ravindu1024
  • 1,496
  • 1
  • 13
  • 30

1 Answers1

7

Use TYPE_APPLICATION_OVERLAY. It is the only window type that Android O allows to be displayed over other apps.

Check this out for an explanation: https://developer.android.com/preview/behavior-changes.html#cwt

Matt Vaughn
  • 191
  • 3
  • Thank you. That was it! I'm actually doing this in an accessibility service and I wonder why TYPE_ACCESSIBILITY_OVERLAY doesn't work. (with the service enabled as a connected accessibility service in settings) – ravindu1024 Jul 31 '17 at 01:41
  • Looks like the link is broken - I think this is the same info though: https://developer.android.com/about/versions/oreo/android-8.0-changes#cwt – rorold Jun 08 '21 at 14:29