-1

What is the most frequently triggered android intent action that my app could have a BroadcastReceiver listening for without a service running in order to receive it?

Background

I have a foreground service that needs to run roughly whenever the user is present at the phone. When the screen gets turned off I shut down the service so Doze mode can be achieved (and yes, foreground running services block Doze mode even though documentation doesn't clearly state so).

The problem comes when trying to turn the service back on.
I've already looked into SCREEN_ON and USER_PRESENT but both appear to require a running background service in order to be received which negates what i am trying to achieve.

So my thought is, I wonder if there's a action triggered frequently enough when the user is present that I could listen for that instead of SCREEN_ON/USER_PRESENT?

paulina_glab
  • 2,467
  • 2
  • 16
  • 25
CamHart
  • 3,825
  • 7
  • 33
  • 69

1 Answers1

0

I've found that the best way to do this is to register a BroadcastReceiver on the "android.intent.action.USER_PRESENT" action.

To distinguish between cases where the user has turned on his screen when it wasn't locked to when he actually unlocked it use the KeyguardManager to check the security settings.

add this in activity

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

and use this :

public class PhoneUnlockedReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        KeyguardManager keyguardManager = (KeyguardManager)context.getSystemService(Context.KEYGUARD_SERVICE);
        if (keyguardManager.isKeyguardSecure()) {

            //do stuff here                
        }
    }
}

Happy coding!!

Hemant Parmar
  • 3,924
  • 7
  • 25
  • 49
  • 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. – Hemant Parmar Dec 21 '17 at 12:32
  • i gave suggestion based on you already did with your post. on other you want achieve is may be time consuming with less outcome. – Hemant Parmar Dec 21 '17 at 12:36
  • Your suggestion is exactly what I said I didn't want. – CamHart Dec 21 '17 at 12:39
  • Plus, your answer is an exact copy of https://stackoverflow.com/questions/3446202/android-detect-phone-unlock-event-not-screen-on. Thanks for giving credit to the original author. – CamHart Dec 21 '17 at 12:40