Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reveal that screen is locked?

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?

like image 620
Barmaley Avatar asked May 31 '11 10:05

Barmaley


2 Answers

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);
like image 127
pandre Avatar answered Sep 21 '22 21:09

pandre


There is a better way:

KeyguardManager myKM = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
if( myKM.inKeyguardRestrictedInputMode()) {
 //it is locked
} else {
 //it is not locked
}
like image 43
Shaul Rosenzweig Avatar answered Sep 18 '22 21:09

Shaul Rosenzweig