Search code examples
androidlockscreenandroid-windowmanager

How to change the WindowManager.LayoutParams' type programmatically?


I got a view that I am able to display on the lockscreen. But I want it to make it optional. Currently I use these params to achieve this:

WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT, 
WindowManager.LayoutParams.WRAP_CONTENT, 
WindowManager.LayoutParams.TYPE_SYSTEM_ERROR, 
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED |
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | 
WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH | 
WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, PixelFormat.TRANSPARENT);

And for not showing it on the lockscreen I use

WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT, 
WindowManager.LayoutParams.WRAP_CONTENT, 
WindowManager.LayoutParams.TYPE_PHONE, 
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | 
WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH | 
WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, PixelFormat.TRANSPARENT);

Separately they work fine, but I want to change the type and flags programmatically. So I tried changing the WindowManager.LayoutParams with

params.flags &= ~WindowManager.LayoutParams.TYPE_SYSTEM_ERROR;
params.flags &= ~WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED;
params.flags |= WindowManager.LayoutParams.TYPE_PHONE;
windowManager.updateViewLayout(myView,params);

to remove the type, remove the flag and set a new type, but that doesn't seem to work. Does anyone know how to do this correctly?


Solution

  • You are setting type values into flag. Try this instead:

    params.flags &= ~WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED;
    
    // type is no bit flag, so this should do it
    params.type = WindowManager.LayoutParams.TYPE_PHONE;