Programmatically turn screen on in android

别说谁变了你拦得住时间么 提交于 2019-11-28 21:38:07

I started off much like you, and the window flags didn't really work.

I finally got it to work by using two Android services: KEYGUARD_SERVICE and POWER_SERVICE:

KeyguardManager km = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
final KeyguardManager.KeyguardLock kl = km.newKeyguardLock("MyKeyguardLock");
kl.disableKeyguard();

PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP
        | PowerManager.ON_AFTER_RELEASE, "MyWakeLock");
wakeLock.acquire();

Don't forget to release the wake lock when you're done with it.

You'll need to request permissions DISABLE_KEYGUARD and WAKE_LOCK

koteswarao

Here is the solution

WindowManager windowManager = (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
    WindowManager.LayoutParams params = new WindowManager.LayoutParams(
            LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT,
            LayoutParams.TYPE_SYSTEM_ALERT |
                    LayoutParams.TYPE_SYSTEM_OVERLAY,
                    LayoutParams.FLAG_NOT_TOUCH_MODAL |
                    LayoutParams.FLAG_SHOW_WHEN_LOCKED |
                    LayoutParams.FLAG_KEEP_SCREEN_ON|
                    LayoutParams.FLAG_DISMISS_KEYGUARD|
                    LayoutParams.FLAG_TURN_SCREEN_ON,
            PixelFormat.TRANSPARENT);

KeyguardManager km = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
    km.isKeyguardLocked();

    windowManager.addView(mTopView, params);
    getWindow().setBackgroundDrawable();

I also suffered from many problems for my app. Actually i want screen lock when user presses the back button twice. and unlock when user presses the home button.

For unlock the device marmor's code is right. :) I've used this code.

PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); 
                WakeLock wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK
                                                 | PowerManager.ACQUIRE_CAUSES_WAKEUP
                                                 | PowerManager.ON_AFTER_RELEASE, "MyWakeLock");
                wakeLock.acquire();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!