Android - detect phone unlock event, not screen

Is there any way to detect when the user unlocks the phone? I know about ACTION_SCREEN_ON and ACTION_SCREEN_OFF , but they seem to be triggered when the screen turns on / off when you press the power button, but not really when the phone unlocks when you press the menu button ...

I am trying to detect an unlock / lock while running, and I want to resume action after unlocking.

+46
android
Aug 10 '10 at 5:09
source share
4 answers

Here's what to do:

Suppose you want to detect an 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 activity will be called when ACTION_SCREEN_ON is activated. Create a handler and wait for ACTION_USER_PRESENT. When he is fired, implement what you want for your work.

Credit is sent to CommonsWare here: Android - What happens when the device is unlocked?

+58
Aug 10 '10 at 17:54
source share
— -

After some time debugging, I found that the best way to do this is to register the BroadcastReceiver in the action "android.intent.action.USER_PRESENT".

"Broadcast Action: Dispatched when a user is present after waking the device (for example, when the keyboard is gone)."

To distinguish between cases when the user turned on his screen, when he was not locked, when he really unlocked, use the KeyguardManager to check the security settings.

Code example:

Add this to your activity:

 registerReceiver(new PhoneUnlockedReceiver(), new IntentFilter("android.intent.action.USER_PRESENT")); 

Then use this class:

 public class PhoneUnlockedReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { KeyguardManager keyguardManager = (KeyguardManager)context.getSystemService(Context.KEYGUARD_SERVICE); if (keyguardManager.isKeyguardSecure()) { //phone was unlocked, do stuff here } } } 
+16
Feb 24 '15 at 11:45
source share
 public class PhoneUnlockedReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(Intent.ACTION_USER_PRESENT)){ Log.d(TAG, "Phone unlocked"); }else if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)){ Log.d(TAG, "Phone locked"); } } } 

register the receiver using this operator

 receiver = new PhoneUnlockedReceiver(); IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_USER_PRESENT); filter.addAction(Intent.ACTION_SCREEN_OFF); registerReceiver(receiver, filter); 
+5
Nov 20 '16 at 9:44
source share

Not tested, but try the following:

  • Wait ACTION_SCREEN_ON .
  • (After the screen is turned on,) Wait for ACTION_MAIN with the CATEGORY_HOME category (which launches the main screen). This is probably what was sent after unlocking the phone.

The first step is to filter out the usual HOME key presses.

+1
Aug 10 '10 at 5:26
source share



All Articles