I can't receive broadcast on battery state change?

Zardaloop picture Zardaloop · Jun 30, 2012 · Viewed 17.5k times · Source

I am having the exact same problem as this post: Battery broadcast receiver doesn't work. But it seems no one has answered that question.

Here is my BroadcastReceiver:

public class BatteryLevelReceiver extends BroadcastReceiver{


    @Override
    public void onReceive(Context context, Intent intent) {
    Log.v("plugg", "plug change fired");
    Toast.makeText(context, " plug change fired", Toast.LENGTH_LONG).show();
        }

And here is my AndroidManifest.xml:

<receiver android:name=".ReceversAndServices.BatteryLevelReceiver">
               <intent-filter android:priority="900">
               <action android:name="android.intent.action.BATTERY_LOW" />

               </intent-filter>
           </receiver>

           <receiver android:name=".ReceversAndServices.BatteryLevelReceiver">
               <intent-filter android:priority="900">
               <action android:name="android.intent.action.BATTERY_CHANGED" />
               </intent-filter>
           </receiver>

I have also added this line to the manifest:

<uses-permission android:name="android.permission.BATTERY_STATS"/>

But still no success!

I would really appreciate if someone could advise me what I am doing wrong.

Answer

Darshan Rivka Whittle picture Darshan Rivka Whittle · Jun 30, 2012

From the documentation for ACTION_BATTERY_CHANGED:

You can not receive this through components declared in manifests, only by explicitly registering for it with Context.registerReceiver(). See ACTION_BATTERY_LOW, ACTION_BATTERY_OKAY, ACTION_POWER_CONNECTED, and ACTION_POWER_DISCONNECTED for distinct battery-related broadcasts that are sent and can be received through manifest receivers.

There you have it: you must explicitly register for it from your Java code.