How to reveal that screen is locked?
Asked Answered
S

3

9

In my application I need to know when device is locked (on HTC's it looks like short press on "power" button). So the question is: which event is triggered when device is locked? Or device is going to sleep?

Stripe answered 31/5, 2011 at 10:57 Comment(0)
U
5

You should extend BroadcastReceiver and implement onReceive, like this:

public class YourBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (Intent.ACTION_SCREEN_OFF.equalsIgnoreCase(intent.getAction())) {
            //screen has been switched off!
        }
    }
}

Then you just have to register it and you'll start receiving events when the screen is switched off:

IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
appBroadcastReceiver = new AppBroadcastReceiver(yourActivity);
registerReceiver(appBroadcastReceiver, filter);
Underprop answered 31/5, 2011 at 11:6 Comment(1)
If you're wanting to check if the device is locked, you could use the method from this solution. Unfortunately there's no broadcast for the device locking, but I find it useful to be able to check if it's locked or not.Shanleigh
P
3

There is a better way:

KeyguardManager myKM = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
if( myKM.inKeyguardRestrictedInputMode()) {
 //it is locked
} else {
 //it is not locked
}
Prink answered 29/12, 2011 at 13:45 Comment(1)
Did you try isDeviceLocked for Android 5.1 developer.android.com/reference/android/app/…?Durant
F
0

In addition to the above answer, in-case you want to trigger some action when your app is at the foreground:

You could use the event called onResume() to trigger your own function when your app takes the spotlight from a previously resting state, i.e, if your app was at the background(paused/minimized...)

protected void onResume()
{
    super.onResume();

    //call user-defined function here
}
Ferrocyanide answered 31/5, 2011 at 11:18 Comment(2)
No, it's not suitable, since onResume() called everytime when activity starts, so there's no clue either it comes after sleeping or just creatingStripe
yup. definitely. just a suggestion :)Ferrocyanide

© 2022 - 2024 — McMap. All rights reserved.