i need to know (throught my app) if the Android device is charging. Any ideas? thanks
Asked
Active
Viewed 7,489 times
3 Answers
8
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;
}
JPM
- 8,741
- 13
- 76
- 132
5
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;
Alberto Zaccagni
- 29,658
- 11
- 72
- 103
Deepak Rama
- 91
- 3
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);
}
capellone78
- 1,151
- 1
- 7
- 2