我正在尝试检测设备当前是否正在充电,但此代码始终将isCharging
变量设置为false
:
public class PowerReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent)
{
int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL;
int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
if (isCharging)
{
Toast.makeText(context, "Charging", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "Not charging", Toast.LENGTH_LONG).show();
}
}
}
答案 0 :(得分:6)
基本上You cannot register for ACTION_BATTERY_CHANGED via the manifest
。以编程方式注册
参见这些链接肯定会有所帮助:)
Battery status is always not charging
https://github.com/commonsguy/cw-omnibus/tree/master/SystemEvents/OnBattery
http://developer.android.com/training/monitoring-device-state/battery-monitoring.html