Search code examples
javaandroidbatterylevelbatterymanager

Null Pointer Warning - BatteryManager.EXTRA_LEVEL


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)?


Solution

  • The Javadoc for registerReceiver states:

     * @return The first sticky intent found that matches <var>filter</var>,
     *         or null if there are none.
    

    So there is the potential that this will return you a null event. You already handle the case where the values are invalid ((level == -1 || scale == -1)), so I would recommend that you just check whether the intent is null, and return that value early:

    if (batteryIntent == null) {
        return -1;
    }