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.