Search code examples
androidbroadcastreceiver

Not able to get actions to fire USER_PRESENT or SCREEN_ON Android Emulator


I want to know when a user has turned their phone on eg. click the power button/possibly actually unlocked their phone. The ultimate goal is to update a widget's display after calling an API vs. using scheduled updates.

The issue is I've been scouring threads and I have not been able to get my logs to fire in Logcat. I have tried both Receiver and Service methods. Is what Is what I am attempting possible?

I have also tried setting the READ_PHONE_STATE permission in the manifest.

Some code context of what I have:

Manifest:

<receiver android:name=".CustomBroadcastRecveiver">
  <intent-filter>
    <action android:name="android.intent.action.USER_PRESENT">
    <action android:name="android.intent.action.SCREEN_ON">
  </intent-filter>
</receiver>

Optional service in manifest that I tried:

<service android:naem=".CustomService"/>

CustomBroadcastReceiver:

public class CustomBroadcastReceiver extends BroadcastReceiver {
  @Override
  public void onReceive(Context context, Intent intent) {
    Log.i("MyTag", "broadcast receive"); // this does not run

    if (intent.getAction().equals(Intent.ACTION_USER_PRESENT) {
      Log... // this doesn't run, same for ACTION_SCREEN_ON that would be in a new if block
    }
  }
}

I'm open to other alternatives. I can provide more context if necessary. I can expand more on my service implementation if that is the way to go assuming what I'm after is possible.

Edit To add more context on how I used Elletlar's answer

In my MainActivity I added:

private static Context context;

Then inside onCreate:

context = getApplicationContext();
// instantiate my specific receiver
// set the code from answer below

Note: I am API 29 if it makes any difference.


Solution

  • From the "android.intent.action.SCREEN_ON" docs, "You cannot receive this through components declared in manifests, only by explicitly registering for it with

    Context#registerReceiver(BroadcastReceiver, IntentFilter).
    

    Example of registering explicitly:

    myReceiver = new MyReceiver();
    IntentFilter filter = new IntentFilter();
    filter.addAction(Intent.ACTION_SCREEN_OFF);
    filter.addAction(Intent.ACTION_SCREEN_ON);
    registerReceiver(myReceiver, filter);