Search code examples
androidlockscreen

How to call android default LockScreen?


How to call android's default LockScreen in activity or service?

I create android application what is like a Optimus G2's knock on function. But I have some problem. My Activity has OnStop() or OnDestroy() function, i won't it's call default LockScreen or Sleep and wake. First, I try PowerManager.gotoSleep(), but it's Android system API. Solution is DevicePolicyManager but I won't use it.


Solution

  • Have a look into the Device Administration API: http://developer.android.com/guide/topics/admin/device-admin.html#top

    When admin, you can use the Device Policy Manager and lockNow() to lock the screen: http://developer.android.com/reference/android/app/admin/DevicePolicyManager.html#lockNow%28%29

    To unlock, you have to use the windowmanager to add a flag to the current window.

    WindowManager windowManager = Context.getSystemService(Context.WINDOW_SERVICE);
    Window window = getWindow();
    window.addFlags(windowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);  
    

    To turn your screen on:

    PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    wakeLock = powerManagernewWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE, "wakeLock");
    wakeLock.acquire();
    

    Don't forget the WAKE_LOCK permission in your manifestfile.