i need to know (throught my app) if the Android device is charging. Any ideas? thanks
Asked
Active
Viewed 7,789 times
3 Answers
9
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
- 9,077
- 13
- 78
- 137
-
very nice. tested and works on Samsung A13 in 2022 – save_jeff Nov 08 '22 at 07:49
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
- 30,779
- 11
- 72
- 106

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,201
- 1
- 8
- 2