Determine the current charge status
Intentfilter ifilter =NewIntentfilter (intent.action_battery_changed); Intent BATTERY = Context.registerreceiver (NULL, IFilter);//Are you chargingintStatus =Battery. Getintextra (Batterymanager.extra_status,-1); Boolean ischarging= Status = = Batterymanager.battery_status_charging | |Status==Batterymanager.battery_status_full;//USB or AC charger? intChargeplug =Battery. Getintextra (Batterymanager.extra_plugged,-1); Boolean Usbcharge= Chargeplug = =Battery_plugged_usb;boolean Accharge= Chargeplug = = Battery_plugged_ac;
Determine the current battery charge
battery. Getintextra (Batterymanager.extra_level,-1battery. Getintextra ( Batterymanager.extra_scale,-1); float batterypct = level/(float) scale;
Monitor the change in charging status
1. Register in Manifest
<receiverAndroid:name=". Powerconnectionreceiver "> <Intent-filter> <ActionAndroid:name= "Android.intent.action.ACTION_POWER_CONNECTED"/> <ActionAndroid:name= "Android.intent.action.ACTION_POWER_DISCONNECTED"/> </Intent-filter></receiver>
Public classPowerconnectionreceiverextendsBroadcastreceiver {@Override Public voidOnReceive (Context context, Intent Intent) {intStatus = Intent.getintextra (Batterymanager.extra_status,-1); Booleanischarging = Status = = Batterymanager.battery_status_charging | |Status==Batterymanager.battery_status_full; intChargeplug = Intent.getintextra (batterymanager.extra_plugged, 1); BooleanUsbcharge = Chargeplug = =Battery_plugged_usb; BooleanAccharge = Chargeplug = =Battery_plugged_ac; }}
Monitor significant changes in battery power
Monitor device entry or end of low battery state
The following manifest snippet extracts the intent filter element from the broadcast sink. By listening ACTION_BATTERY_LOW
and ACTION_BATTERY_OKAY
, the system triggers the receiver as long as the device's battery enters or ends a low power state .
<receiver android:name= ". Batterylevelreceiver "><intent-filter> <action android:name=" android.intent.action.ACTION_ Battery_low "/> <action android:name=" Android.intent.action.ACTION_BATTERY_OKAY "/> </ Intent-filter></receiver>
Monitor battery power and charge status