private void setUnlocked() 
    { 
        Window win = getWindow(); 
        WindowManager.LayoutParams winParams = win.getAttributes(); 
        winParams.flags |= (WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD 
            | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED 
            
            //| WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON 
                        | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON); 
        win.setAttributes(winParams); 
    } 

       private void setLocked() { 
        Window win = getWindow(); 
        WindowManager.LayoutParams winParams = win.getAttributes(); 
        winParams.flags &= (~WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD 
                & ~WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED 
                //& ~WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON 
                & ~WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON); 
        win.setAttributes(winParams); 
    }

        km  = (KeyguardManager)getSystemService(Context.KEYGUARD_SERVICE);
        if(km.inKeyguardRestrictedInputMode()){
            setUnlocked();// screen is locked,keeping this UI can not be locked
        } else {
            setLocked();// screen is unlocked,keeping this UI can be locked
        }