这是一个非常棘手的问题。Android Developer 上的相关代码有错误。
基本上,您可以在此链接上了解如何检测它:
https://developer.android.com/training/monitoring-device-state/battery-monitoring.html
您可以使用方法 OnReceive(Context context, Intent intent){}
通过广播接收器检测它是否正在充电和电池电量不足
但是,这个链接有一个错误,用于监控重大变化。[注意这里,动作名称是android.intent.action.ACTION_BATTERY_LOW]
[1]
但让我们看看 Intent 是如何描述的。
ACTION_BATTERY_LOW
在 API 级别 1 中添加
字符串 ACTION_BATTERY_LOW
广播操作:指示设备上的电池电量不足。此广播对应于“低电量警告”系统对话框。
这是一个受保护的意图,只能由系统发送。
常量值:“android.intent.action.BATTERY_LOW”
您可以在 Android Developers Intent 中找到它。
换句话说,这里发生了错误。它应该是 action.BATTERY_LOW 而不是 action.ACTION_BATTERY_LOW。所以你在 AndroidManifest 中的代码应该是:
<receiver android:name=".receiver.BatteryLevelReceiver">
<intent-filter>
<action android:name="android.intent.action.BATTERY_LOW"/>
<!--instead of android.intent.action.ACTION_BATTERY_LOW-->
</intent-filter>
</receiver>
还要确保您的接收器是正确的。
public class BatteryLevelReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "BAttery's dying!!", Toast.LENGTH_LONG).show();
Log.e("", "BATTERY LOW!!");
}
}
很难在笔记本电脑上调试或登录,使用 Toast 可能会有所帮助。
Toast.makeText(context, "BAttery's dying!!", Toast.LENGTH_LONG).show();
//Toast.makeText(Context context, String str, Integer integer).show();
希望它能帮助你解决问题。