i need to know (throught my app) if the Android device is charging. Any ideas? thanks
One thing I found out is that if your phone has 100% battery level you won't get the charging notification. Some people mean charging and others mean when it has external power, whether its 100% or not. I lumped these into one and if any condition is true then I return true.
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;
}
Here's the code that worked:
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;
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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.