My intention is to keep the usb / power cable Android device settings in the current state: connected / disconnected. From the developer's site, I see that there are two intentions for obtaining this status: ACTION_POWER_CONNECTED / DISCONNECTED. Therefore, I used the same code as in Developers:
http://developer.android.com/training/monitoring-device-state/battery-monitoring.html
under "Changes to the monitor while it is charging."
manifest
<receiver android:name=".PowerConnectionReceiver"> <intent-filter> <action android:name="android.intent.action.ACTION_POWER_CONNECTED"/> <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"/> </intent-filter> </receiver>
Java code
public class PowerConnectionReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1); boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB; boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC; Toast.makeText(context, "pvr = " + usbCharge + ", " + acCharge + "," + isCharging, Toast.LENGTH_SHORT).show(); } }
When I plug in the USB IN / OUT cable and the broadcast is always sent correctly and gets into the PowerConnectionReceiver, but always with the same result (= cable connected).
I tested it with Galaxy Nexus 4.1.1 / 4.2.1. I always get 2xFALSE in Toast (chargePlug = FALSE, usbCharge = FALSE).
Why does intent.getIntExtra (BatteryManager.EXTRA_PLUGGED, -1) always return the default value of -1?
Thanks.
ps. everything works fine if I register the receiver in Java
Intent intent = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
... in service or in action. But, according to the Android developer site, there is no need to do the code above to return the correct value;