Search code examples
javaandroidpopupfloatingandroid-windowmanager

Floating window from service over locked screen in API 26 and higher


I need to show floating window with text view on calling number this working fine on locked screen and unlocked on lower API (than 26) what the right way to show floating window on API 26 and higher on locked screen while running the code from service?

This code is working for unlocked screen for API 26+

if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O){
            windowParams2 = new WindowManager.LayoutParams(
                    WindowManager.LayoutParams.WRAP_CONTENT,
                    WindowManager.LayoutParams.WRAP_CONTENT,
                    WindowManager.LayoutParams.TYPE_SYSTEM_ERROR,
                    WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                    PixelFormat.TRANSLUCENT);
            windowParams2.x = 0;
            windowParams2.y = 0;
            windowParams2.gravity = Gravity.CENTER;

        }else{

            windowParams2 = new WindowManager.LayoutParams(
                    WindowManager.LayoutParams.WRAP_CONTENT,
                    WindowManager.LayoutParams.WRAP_CONTENT,
                    WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
                    WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE ,
                    PixelFormat.TRANSLUCENT);
            windowParams2.x = 0;
            windowParams2.y = 0;
            windowParams2.gravity = Gravity.CENTER;
        }


Solution

  • Add the following flags:

    WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
    

    Also don’t forget if you want this to work properly you need to add some permissions to your manifest:

    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
    <uses-permission android:name="android.permission.WAKE_LOCK" />