I'm trying to create an accessibility HUD that overlays with translucent colors the system.
I have a Service that calls my HUD class (which is another Service)
startService(new Intent(getApplicationContext(), HUD.class));
My HUD Service class:
@Override
public void onCreate() {
super.onCreate();
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
filter = new View(this);
float alpha = (float) 0.8;
filter.setAlpha(alpha);
filter.setBackgroundColor(Color.RED);
filter.getBackground().setAlpha(80);
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
-1, // Match parent
-1, // Match parent
WindowManager.LayoutParams.TYPE_ACCESSIBILITY_OVERLAY,
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE |
WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH |
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.TOP;
params.x = 0;
params.y = 100;
windowManager.addView(filter, params);
}
This code however, only works if I change WindowManager.LayoutParams.TYPE_ACCESSIBILITY_OVERLAY to WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY, however that is not what I want. The error I receive is:
Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?
I have tried changing the way I get the context as suggested in multiple links, from getApplicationContext() to MyActivity.this (for that I had moved my HUD Service class to an Activity for the sole purpose of getting the context in a different way. That still gave me the same crash and it disappears if I don't flag the window as an accessibility overlay.