I am having a little trouble getting whether a device is charging or not, but only on some devices. Namely the Sony Xperia Z and Xperia E.
The battery status always reports the phone as plugged out. I have tested the app on a Samsung Galaxy S4 and a Galaxy S2 and it works correctly on those.
I have a BroadcastReceiver, PowerConnectionReceiver, which is registered in the manifest to receive plugged in/plugged out events. When the receiver gets an intent, it calls another intent to get the current battery status:
@Override
public void onReceive(Context c, Intent intent) {
Context context = c.getApplicationContext();
try{
IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = context.registerReceiver(null, ifilter);
int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING;
int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
Toast.makeText(context, "Battery charging " + isCharging , Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Log.e(TAG, e.toString());
}
Can anybody see any obvious flaw in that code? I am stumped. Both the Sony Xperia Z I tried it on (where it doesn't work correctly) and the Samsung Galaxy S4 I tried it on are running Android 4.2.
You are assuming that
ACTION_BATTERY_CHANGED
has been broadcast, reflecting the new charging status, before whatever broadcast you are listening to ("plugged in/plugged out events") has been broadcast. I am not aware that this is a requirement. If the device sends its "plugged in/plugged out events" beforeACTION_BATTERY_CHANGED
, your code will be seeing the lastACTION_BATTERY_CHANGED
, before the "plugged in/plugged out event".