I'm using the code from the below example page in my app to monitor when the device is connected / disconnected to a power adapter:
http://developer.android.com/training/monitoring-device-state/battery-monitoring.html
So I have in my manifest:
<receiver android:name=".StatusChangeReceiver">
<intent-filter>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED"/>
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"/>
</intent-filter>
</receiver>
And my class looks like this:
public class StatusChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
boolean isActive = prefs.getBoolean("isActive", false);
if (isActive){
int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL;
// Do somthing with isCharging here
}
}
But isCharging is always false, regardless of whether the power was connected or disconnected. I'm obviously having problems debugging this as I have to keep (dis)connecting the USB cable to get the event to fire.
I presume when the power is connected the event is fired and the status isn't updated before my code runs, but I'm not sure of the best way to resolve it. Any ideas?