Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting when screen is locked

Tags:

android

screen

I've seen a couple of posts on here on how to check if the screen is locked, but none of it has been working for me. It all detects if the actual screen is off or not (not if it's locked).

I have a game in which music plays. When the lock button is pressed, it continues to play. I originally had the music stopping in OnStop, but the application would restart after getting locked, so the music would eventually start up again.

Then, I added KeyboardHidden|orientation to the manifest. This makes it so it doesn't restart the app, but OnStop doesn't seem to get called anymore.

I've tried using PowerManager to see if the screen is on/off, which works, but doesn't help. (I can get the music to stop there, but as soon as you hit the lock button again, the music starts right back up)

like image 804
Ryan Avatar asked Nov 29 '11 20:11

Ryan


People also ask

How can I be notified when my screen is locked?

Open your phone's Settings app. Notifications. Under "Lock screen," tap Notifications on lock screen or On lock screen. Choose Show alerting and silent notifications.

What does appear on the monitor when Windows is locked on?

The Windows spotlight image should appear on the lock screen. If you don't see the Windows spotlight image when you're signing in, select Start > Settings > Personalization > Lock screen . Then make sure Show lock screen background picture on the sign-in screen is turned on.

Is the lock screen a flutter?

Flutter Screen Lock. This Flutter plugin provides an feature for screen lock. Enter your passcode to unlock the screen. You can also use biometric authentication as an option.


2 Answers

There is a better way:

KeyguardManager myKM = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE); if( myKM.inKeyguardRestrictedInputMode()) {  //it is locked } else {  //it is not locked } 

No need for broadcastRecievers, permissions or anything similar.

Note: It doesn't work when user has set his/her screen lock to none in settings-->security-->screenlock-->none

like image 171
Shaul Rosenzweig Avatar answered Oct 13 '22 14:10

Shaul Rosenzweig


This link might be helpful to others for two things at one place.

Check if the Device is Locked Or Not:

KeyguardManager myKM = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE); boolean isPhoneLocked = myKM.inKeyguardRestrictedInputMode(); 

(Note: above method doesn't work if screenlock is set to none in settings-->security-->screenlock.)

Check If Device is Awake or in Sleep Mode:(for Sdk Version > L Preview < Sdk Version)

PowerManager powerManager = (PowerManager)context.getSystemService(Context.POWER_SERVICE); isScreenAwake = (Build.VERSION.SDK_INT < 20? powerManager.isScreenOn():powerManager.isInteractive()); 
like image 24
Sagar Shah Avatar answered Oct 13 '22 14:10

Sagar Shah