Get Battery Percentage in Android – Different Methods

By | July 20, 2017

We will see the different ways to get the battery percentage in Android.

Method 1

Register a Broadcast Receiver

   IntentFilter iFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
   // Register the broadcast receiver
   registerReceiver(mBroadcastReceiver, iFilter);

Receive like this

private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // get the battery level
            int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
            Log.i(TAG, "Battery : " + level + "%");
        }
    };

Method 2

BatteryManager bm = (BatteryManager)getSystemService(BATTERY_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
    int batLevel = bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
}

Method 3

 public static int getBatteryPercentage(Context context) {

        IntentFilter iFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        Intent batteryStatus = context.registerReceiver(null, iFilter);

        int level = batteryStatus != null ? batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) : -1;
        int scale = batteryStatus != null ? batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1) : -1;

        float batteryPct = level / (float) scale;

        return (int) (batteryPct * 100);
    }

Note : Make sure you unregister the receiver when you don’t need.

Leave a Reply

Your email address will not be published. Required fields are marked *