Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the screen is locked in android

Tags:

android

For my application, I need to know that the screen is locked. How to check this is problematically. I used following flag:

if(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON != 0){
    // some code
}else if((WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED)!= 0){
   // some code
}

But this always executing both if and else part... which flag I have to use to check the screen is locked or not?

like image 317
Prasad Avatar asked Jan 25 '12 11:01

Prasad


3 Answers

KeyguardManager myKeyManager = (KeyguardManager)getSystemService(Context.KEYGUARD_SERVICE);

if( myKeyManager.inKeyguardRestrictedInputMode()) {

 //screen is locked

} else {

 //screen is not locked

}
like image 168
Vaishali Sutariya Avatar answered Nov 01 '22 17:11

Vaishali Sutariya


I'll try to answer this though the question is already old since it is unresolved and could help other googlers. ;)

First you must register a BroadcastReceiver for Intent.ACTION_SCREEN_OFF & Intent.ACTION_SCREEN_ON. Note that this receiver must be registered in codes and will not work when declared in the manifest.

In your broadcast receiver, when you receive Intent.ACTION_SCREEN_ON, you can check if the screen is locked by using the below codes:

KeyguardManager km = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
boolean locked = km.inKeyguardRestrictedInputMode();
like image 23
Macchiato Avatar answered Nov 01 '22 19:11

Macchiato


Register a broadcast receiver with action android.intent.action.ACTION_SCREEN_OFF and write your code in onReceive() method of receiver.

If you are using an activity, onPause() will be called when the screen locked and onResume() will be called when the screen unlocked.

In your code you are checking some flags, i don't know where you will do that checking ? is it continuous verification ? If you are using an activity in your app, the above procedure will happen, just check it in Android Developers website.

like image 1
Yugandhar Babu Avatar answered Nov 01 '22 19:11

Yugandhar Babu