I am attempting to get the device's current battery level with the following:
Intent batteryIntent = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
int level = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
Log.i(LOG_FILTER, "Battery level = " + (level*100)/scale);
// error check values
if (level == -1 || scale == -1) {
return -1;
} else {
return (level * 100) / scale;
}
The code seems to work and has never failed me, but I am getting a warning:
Method invocation 'batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)' may produce 'java.lang.NullPointerException'
This may never actually affect my application but as there is an end product depending on it, I am wondering, how might I accommodate this potential issue? Is there a way to reorganize the above to achieve the same result (obtaining the battery's current state of charge)?