电池广播接收器不工作 [英] Battery broadcast receiver doesn't work

查看:217
本文介绍了电池广播接收器不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道为什么,但我的电池广播接收机无法正常工作。

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

AndroidManifest.xml中

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

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();      
    }
}

什么是错我的code?
我使用控制台(远程登录)更改电池电量(电源容量X)。

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

推荐答案

有几个问题;我粗略地通过降低严重性命令他们:

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


  1. 您不能注册为 ACTION_BATTERY_CHANGED 从你的清单;您的必须的编程方式注册吧。

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

不要使用 BATTERY_STATS 许可;这是完全无关的。

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

如果你在同一个广播接收器接收多个广播(即使你不是它通常是一个好主意),你应该检查,看看哪些广播你刚刚收到的。 ACTION_BATTERY_LOW 不应该以同样的方式对待 ACTION_BATTERY_CHANGED 。 (一方面,它不具备 BatteryManager.EXTRA_LEVEL 额外重视它,所以想读它会给你默认值, 0

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

您应该使用 1 为默认值,如 0 不是一个有效的值。

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

您应该检查,看看您是否已经收到了默认值,并适当地处理它。

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

您应该使用 BatteryManager.EXTRA_LEVEL ,而不是硬编码级别。

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

这篇关于电池广播接收器不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆