简体   繁体   中英

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

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;
}

I would throw a try/catch around it because you know it could throw the error, and then you can handle it appropriately if/when it ever does occur.

try {
    //your code here
} catch (NullPointerException e) {
    //handle the error here, maybe return -1?
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM