0

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.

Aamirkhan
  • 5,746
  • 10
  • 47
  • 74
Amadas
  • 703
  • 1
  • 5
  • 10

1 Answers1

1

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.

randomizer
  • 1,619
  • 3
  • 15
  • 31
  • I try use device administration api, so i have sleep my phone. But I don't know how screen on my Phone. Do you know it? – Amadas Mar 05 '14 at 08:18
  • Calling "lockNow()" from the Device Policy Manager should to the trick. – randomizer Mar 05 '14 at 08:26
  • I don't understand your comment. I called "lockNow()", phone is screen off and lock. But I don't know how to auto screen turn on. I set DevicePolicyManager.setMaximumTimeToLock(ComponentName, msTime) but it doesn't work I want. I has someting wrong. – Amadas Mar 05 '14 at 08:55
  • Ok, so you managed to lock it and want to unlock it? I couldn't make that up from your question. I updated the answer. – randomizer Mar 05 '14 at 09:00
  • Hmm... I don't want unlock it. Just screen is turn on, I show default lockscreen. – Amadas Mar 05 '14 at 09:08
  • Then you should call the lockscreen function and afterwards use the powermanager to show the screen, I added PowerManager code to the answer. – randomizer Mar 05 '14 at 09:18
  • Thank you! I won't it. I try this function many time but I didn't. Your help is very useful to me. – Amadas Mar 05 '14 at 09:22