Search code examples
javaandroidandroid-7.1-nougat

Getting android battery information programmatically


I am trying to get the battery information mainly power left, voltage, current for an android N(7.1.1) device. I am trying to run the following code in onCreate method.

First approach;

IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        batteryStatus = this.registerReceiver(null, ifilter);
        double currentNow = BatteryManager.BATTERY_PROPERTY_CURRENT_NOW;
        double voltage = BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE;
        double level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
        double scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, 

Second approach:

 BatteryManager mBatteryManager =
                (BatteryManager)Context.getSystemService(Context.BATTERY_SERVICE);
        Long energy =
                mBatteryManager.getLongProperty(BatteryManager.BATTERY_PROPERTY_ENERGY_COUNTER);

First approach is giving me the default values and second approach is giving me error: non-static method getsystemservice(string) cannot be referenced from a static context


Solution

  • Have you tried someting like this:

    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // Get the battery scale
            int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE,-1);
    
            // get the battery level
            int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL,-1);
    
        }
    };
    

    And in your on create method:

    IntentFilter iFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);    
    mContext.registerReceiver(mBroadcastReceiver,iFilter);