'How do you get an Android accessibility service to draw overlays over the entire screen?

There's a popular app called Twilight: Blue light filter that draws a red overlay over the entire screen, including both the navigation bar and the status bar. It does this using an accessibility service. How? I've been trying to replicate it for days but I can't get it right. This is what I have inside my own accessibility service:

private void drawTheOverlay(Drawable drawable) {

    WindowManager windowManager = (WindowManager) this.getSystemService(Service.WINDOW_SERVICE);
    View view = new LinearLayout(this);

    view.setClickable(false);
    view.setFocusable(false);
    view.setFocusableInTouchMode(false);
    view.setLongClickable(false);
    view.setKeepScreenOn(false);

    Display display = windowManager.getDefaultDisplay();
    Point realScreenSize = new Point();
    display.getRealSize(realScreenSize);

    WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
    layoutParams.height = realScreenSize.y;
    layoutParams.width = realScreenSize.x;
    
    layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
            | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
            | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
            | WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
    
    layoutParams.format = PixelFormat.TRANSLUCENT;
    layoutParams.windowAnimations = android.R.style.Animation_Toast;
    layoutParams.type = WindowManager.LayoutParams.TYPE_ACCESSIBILITY_OVERLAY;

    view.setBackground(drawable);

    windowManager.addView(view, layoutParams);
    view.setVisibility(View.VISIBLE);
}

The problem with the above code is that the overlay gets vertically offset by some unknown amount. This is how it looks like on my own device, a Razer Phone 2, and as you can see the dark overlay is pushed upwards by a bit:

enter image description here

I've also tried it on a Galaxy S10 and it's the same issue but in the opposite direction. Meaning the overlay is pushed downwards instead of upwards.

How does the Twilight app do it?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source