BroadcastReceiver mBatteryReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
String batteryPercentage = String.valueOf(level);
Log.d("battery",batteryPercentage);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING;
Log.d("ischarging", String.valueOf(isCharging));
int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
String action = intent.getAction();
int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
if (plugged == BatteryManager.BATTERY_PLUGGED_AC && DefaultManager.acChargeConnect && level >= DefaultManager.batteryPercentageTriggerValue) {
//do something
} else if (plugged == BatteryManager.BATTERY_PLUGGED_USB && DefaultManager.usbConnect){
//do something
} else if (plugged == 0) {
// on battery power
} else {
// intent didnt include extra info
}
}
};
所以我想检测电源线或 USB 线何时断开,并在该事件发生时做一些事情。我浏览了BatteryManager
文档并尝试了其中提到的一些常量,但似乎没有任何效果。我想捕获充电器断开事件来做某事。任何指针表示赞赏。谢谢