Android Broadcast Receiver Not Working

2019-06-09 11:24发布

问题:

I am trying to make my app print something to log when screen is turned on but it doesn't work as I expected.

Here is what I have in my Manifest file

<application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity ...>
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>


    <receiver android:name="PhoneBroadcastReceiver" android:enabled="true">
        <intent-filter>
            <action android:name="android.intent.action.SCREEN_ON"></action>
        </intent-filter>
    </receiver>
</application>

and my receiver looks like

public class PhoneBroadcastReceiver extends BroadcastReceiver {

public PhoneBroadcastReceiver()
{
}

@Override
public void onReceive(Context _context, Intent _intent) {
    // TODO Auto-generated method stub
    String a = _intent.getAction();


    MessageHandler.log("Received action: " + a); // just a wrapper for printing to a log

}

}

but it prints nothing to the log. I keep pressing my Android power button and the screen turns on / turns off but my message doesn't appear in the log. What am I missing? It looks the same as in examples I found on the web.

回答1:

You cannot listen for ACTION_SCREEN_ON broadcasts via a BroadcastReceiver registered in the manifest. You have to register it via registerReceiver() from a running component. There are fairly few broadcasts with this trait (ACTION_SCREEN_OFF, ACTION_BATTERY_CHANGED, and perhaps ACTION_USER_PRESENT).



回答2:

ACTION_SCREEN_ON won't work if registered via manifest file. You need to register it dynamically.

Ashu singh