Search code examples
javaandroidbroadcastreceiverpower-management

Battery broadcast receiver doesn't work


I don't know why, but my battery broadcast receiver doesn't work.

AndroidManifest.xml

<receiver android:name=".BatteryReceiver" android:enabled="true">
    <intent-filter>
        <action android:name="android.intent.action.BATTERY_CHANGED" />
        <action android:name="android.intent.action.BATTERY_LOW" />
    </intent-filter>
</receiver>

BatteryReceiver.java

public class BatteryReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        int level = intent.getIntExtra( "level", 0 );
        Log.d("Battery", "level: "+level);
        Toast.makeText(context, "Battery low!", Toast.LENGTH_LONG).show();      
    }
}

What is wrong with my code? I'm using console (telnet) to change battery level (power capacity X).


Solution

  • There are several issues; I've ordered them roughly by decreasing severity:

    1. You can't register for ACTION_BATTERY_CHANGED from your Manifest; you must register for it programmatically.

    2. Don't use the BATTERY_STATS permission; it's completely unrelated.

    3. If you're receiving more than one Broadcast in the same BroadcastReceiver (and it's generally a good idea even if you're not) you should check to see which Broadcast you've just received. ACTION_BATTERY_LOW should not be treated in the same way as ACTION_BATTERY_CHANGED. (For one thing, it doesn't have the BatteryManager.EXTRA_LEVEL Extra attached to it, so trying to read it will give you your default value, 0.)

    4. You should use -1 as your default value, not a valid value like 0.

    5. You should check to see if you've received the default value and handle it appropriately.

    6. You should use BatteryManager.EXTRA_LEVEL rather than hard-coding "level".