IT EXPLORIDA

Something To know

Friday, 6 June 2014

Check Battery level in android

You can check the battery level, which could reduce or even stop the frequency of your updates when the battery is almost exhausted.

Retreive the Battery charging state :

For this, you need to call registerReceiver() without registering a BroadcastReceiver because the instance of the BatteryManager broadcasts all battery details in a sticky intent :
IntentFilter intentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = context.registerReceiver(null, intentFilter);

The following code describe how to retreive the current charging status and, if the device is being charged :
// Is the battery charging / charged?
int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
status == BatteryManager.BATTERY_STATUS_FULL;
// How the battery is charging?
int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
boolean isChargingViaUSB= chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
boolean isChargingViaAC = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
Log.d(TAG, "status : " + status);
Log.d(TAG, "battery is Charging : " + isCharging);
Log.d(TAG, "charging via USB : " + isChargingViaUSB);
Log.d(TAG, "charging via AC : " + isChargingViaUSB);

Retreive the current battery level :
As we explained above, the intent broadcasted bye the BatteryManagercontains all details about battery details(status,charge ..etc) :
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
float batteryPct = level / (float) scale;
Log.d(TAG, "level : " + level + "% , batteryPct : "+ batteryPct);

 

 

No comments:

Post a Comment

Awesome Inc. theme. Powered by Blogger.