0

I'm trying to turn off the screen of an Android phone.

I read many other discussions, and tried two ways discribed here: Turn off screen on Android

In fact, what I really need to do is to launch the lock screen (the one that asks for the PIN). I wasn't sure how to do that and couldn't find documentation about it, so I tried to turn off the screen and hoped that it will display the lock screen when I turn the phone back on. Unfortunately, I wasn't able to test my theory.

First option:

PowerManager manager = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = manager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Your Tag");    
wl.acquire();    
wl.release();

Second option:

WindowManager.LayoutParams params = getWindow().getAttributes();   
params.flags |= LayoutParams.FLAG_KEEP_SCREEN_ON;    
params.screenBrightness = 0;    
getWindow().setAttributes(params);   

First option did nothing, and the second option caused my app to crash. In the stack call, I saw a suspicious log: Only the original thread that created a view hierarchy can touch its views. I do call this code from another thread, running in the background (not the main thread).
Is it possible that this is causing the crash? How can I overcome this problem?
Is there another way to programmatically launch the lock screen, without having to turn off the screen?

Community
  • 1
  • 1
Augustina
  • 259
  • 1
  • 4
  • 15
  • post your error logs – Sreehari May 02 '16 at 16:13
  • I don't know how it's done in Android specifically, but most GUI frameworks provide some means for an arbitrary thread to post _tasks_ to a queue where they will be found and executed by the/a GUI event handler thread. – Solomon Slow May 02 '16 at 17:02

1 Answers1

1

In first option, add ACQUIRE_CAUSES_WAKEUP as well. That would wake up the screen and show lock screen.

PowerManager.WakeLock wl = manager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "Your Tag");    

Hope this helps.

Supratim Haldar
  • 2,376
  • 3
  • 16
  • 26
  • Thank you. Unfortunately, it's still doesn't work (nothing happens...). – Augustina May 03 '16 at 08:18
  • Okay, I read the post once again and I might have misunderstood earlier. I think you are trying to do is - lock the screen from your app itself. If that is true, this discussion will be helpful for you - http://stackoverflow.com/questions/14352648/how-to-lock-unlock-screen-programmatically. – Supratim Haldar May 03 '16 at 09:25