问题
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).
回答1:
There are several issues; I've ordered them roughly by decreasing severity:
You can't register for
ACTION_BATTERY_CHANGED
from your Manifest; you must register for it programmatically.Don't use the
BATTERY_STATS
permission; it's completely unrelated.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 asACTION_BATTERY_CHANGED
. (For one thing, it doesn't have theBatteryManager.EXTRA_LEVEL
Extra attached to it, so trying to read it will give you your default value,0
.)You should use
-1
as your default value, not a valid value like0
.You should check to see if you've received the default value and handle it appropriately.
You should use
BatteryManager.EXTRA_LEVEL
rather than hard-coding "level".
来源:https://stackoverflow.com/questions/8582539/battery-broadcast-receiver-doesnt-work