views:

312

answers:

2

Is there a way to detect when a user unlocks the phone? I know about ACTION_SCREEN_ON and ACTION_SCREEN_OFF, but these seem to be fired when the screen switches on/off on pressing the power button, but not actually when the phone gets unlocked on pressing the Menu button...

Edit: I am trying to detect the unlock/lock while an activity is running, and I want to resume the activity once unlocked.

Thanks Chris

A: 

Didn't test it but try the following:

  • Wait for ACTION_SCREEN_ON.
  • (After screen is on,) Wait for ACTION_MAIN with category CATEGORY_HOME (Which launches the home screen) - This is probably what is sent after the phone gets unlocked.

The 1st step is needed to filter out regular HOME key presses.

adamk
But is that going to work on all phones? For eg, on myTouch pressing the Menu button unlocks the phone, some other phones require you to slide across the phone. So is there something that can catch all?
Chris
I believe so - ACTION_MAIN with category CATEGORY_HOME is definitely called in order to run the home screen (i.e. the launcher). There are many Android phones, however, so I can't be 100% sure. Better give it a try and see if it works for you.
adamk
I guess I forgot to mention I am running an activity, and while it is running, I want to lock/unlock the screen and resume the activity once unlocked. Waiting for ACTION_MAIN and CATEGORY_HOME just freezes my activity on unlock.
Chris
Not sure what you mean by freezes. When you lock the phone your activity is paused, and when unlocked it is resumed - so in this specific case (i.e. lock/unlock while you're running), you can probably use these methods to detect what you need.
adamk
A: 

Here's what to do:

Say you want to detect the unlock event and do something in your activity when the phone is unlocked. Have a Broadcast Receiver for ACTION_SCREEN_ON, ACTION_SCREEN_OFF and ACTION_USER_PRESENT.

onResume of the activity will be called when ACTION_SCREEN_ON is fired. Create a handler and wait for ACTION_USER_PRESENT. When it is fired, implement what you want for your activity.

Credit goes to CommonsWare's answer here: http://stackoverflow.com/questions/3462843/android-what-happens-when-device-is-unlocked

Chris