Battery broadcast receiver doesn't work

末鹿安然 提交于 2019-12-23 05:59:31

问题


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:

  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".



来源:https://stackoverflow.com/questions/8582539/battery-broadcast-receiver-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!