In my application I want to check if the phone is charged by socket or usb. For this I created a BroadcastReceiver
with the following code:
Manifest:
<receiver
android:name=".ChargingReceiver"
android:enabled="true" android:exported="false">
<intent-filter>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED"/>
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"/>
</intent-filter>
</receiver>
ChargingReceiver
public void onReceive(Context context, Intent intent) {
int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
boolean acCharge = (chargePlug == BatteryManager.BATTERY_PLUGGED_AC);
boolean usbCharge = (chargePlug == BatteryManager.BATTERY_PLUGGED_USB);
//...
}
My problem is, that the first line of the ChargingReceiver
always return -1
which is the default value I have set. The BroadcastReceiver is called correctly when I plug or unplug my phone, so it looks to me that the intent does not contain the Extra
I try to look up. I have the code from here so it should work.
I also found this answer but it does not help me, because I have to distinguish between USB Charging and socket charging. Any ideas what I have done wrong? BTW I have tested the code with Android Nougat. I think on Lollipop it has worked, but I'm not completely sure...