我需要知道(通过我的应用)Android设备是否正在充电。有任何想法吗?感谢
答案 0 :(得分:8)
我发现的一件事是,如果您的手机具有100%的电池电量,您将无法收到充电通知。有些人意味着充电,而其他人则意味着有外部能力,无论是100%。我把它们混为一体,如果有任何条件是真的,那我就回归真。
public static boolean isPhonePluggedIn(Context context){
boolean charging = false;
final Intent batteryIntent = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
int status = batteryIntent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean batteryCharge = status==BatteryManager.BATTERY_STATUS_CHARGING;
int chargePlug = batteryIntent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
if (batteryCharge) charging=true;
if (usbCharge) charging=true;
if (acCharge) charging=true;
return charging;
}
答案 1 :(得分:5)
以下是有效的代码:
Intent bat = loader.registerReceiver(null, new
IntentFilter(Intent.ACTION_BATTERY_CHANGED));
int level = bat.getIntExtra("level", 0);
int scale = bat.getIntExtra("scale", 100);
return level * 100 / scale;
答案 2 :(得分:0)
public static boolean isBatteryCharging(Context context){
// Check battery sticky broadcast
final Intent batteryIntent = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
return (batteryIntent.getIntExtra(BatteryManager.EXTRA_STATUS, -1) == BatteryManager.BATTERY_STATUS_CHARGING);
}