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?
Asked
Active
Viewed 3,578 times
3 Answers
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);

pandre
- 6,685
- 7
- 42
- 50
-
If you're wanting to check if the device is locked, you could use the method from [this solution](http://stackoverflow.com/questions/4260794/how-to-tell-if-device-is-sleeping/4261021#4261021). 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. – Chris Aug 06 '11 at 22:32
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
}

Shaul Rosenzweig
- 1,221
- 1
- 9
- 8
-
Did you try isDeviceLocked for Android 5.1 http://developer.android.com/reference/android/app/KeyguardManager.html#isDeviceLocked()? – Maksim Dmitriev Apr 03 '15 at 10:05
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
}

Augiwan
- 2,392
- 18
- 22
-
No, it's not suitable, since onResume() called everytime when activity starts, so there's no clue either it comes after sleeping or just creating – Barmaley May 31 '11 at 11:24
-