电池广播接收器无法工作
我不知道为什么,我的电池广播接收器不工作。
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();
}
}
我的代码有什么问题? 我正在使用控制台(telnet)来更改电池电量(电源容量X)。
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).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有几个问题;我按照严重程度从高到低对它们进行了粗略排序:
您无法从清单中注册
ACTION_BATTERY_CHANGED
;您必须以编程方式注册。不要使用
BATTERY_STATS
权限;这是完全不相关的。如果您在同一个 BroadcastReceiver 中接收到多个广播(即使没有,这通常也是一个好主意),您应该检查一下您刚刚收到的是哪一个广播。
ACTION_BATTERY_LOW
不应以与ACTION_BATTERY_CHANGED
相同的方式处理。 (一方面,它没有附加BatteryManager.EXTRA_LEVEL
Extra,因此尝试读取它会为您提供默认值0
。)您应该使用
-1
作为默认值,而不是像0
这样的有效值。您应该检查是否已收到默认值并适当处理它。
您应该使用
BatteryManager.EXTRA_LEVEL
而不是硬编码“level”。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".