Blackberry determine if using external power

2019-08-30 06:12发布

问题:

Is there a way to determine whether or not the Blackberry has a cable plugged in or not? (power/USB)

I have tried a number of things so far...

if(DeviceInfo.BSTAT_IS_USING_EXTERNAL_POWER > 0)
{
// Plugged in
// TODO : Do something
}else{
// Not plugged in
// TODO: Do something else
}

The else is apparently dead code, and this doesn't work at all.

I have however had some luck with the following:

if((DeviceInfo.getBatteryStatus() ^ DeviceInfo.BSTAT_IS_USING_EXTERNAL_POWER) != 0)
{
    // Plugged in
    // TODO : Do something
}else{
    // Plugged in
    // TODO : Do something else
}

Sadly though, it is only effective if the battery is at 100%. As soon as it drops below, it has the opposite effect.

The latter was compiled using a related issue on SO, however it does not have the desired results as suggested there.

回答1:

This is what I've used in the past:

    private boolean isBatteryCharging(){
        int battst = DeviceInfo.getBatteryStatus();
        if(((battst & DeviceInfo.BSTAT_IS_USING_EXTERNAL_POWER) != 0) 
            || ((battst & DeviceInfo.BSTAT_CHARGING) != 0) 
            || ((battst & DeviceInfo.BSTAT_AC_CONTACTS) != 0)){
            return true;
        }
        return false;       
    }

Hope it helps.



回答2:

Are you sure you should be using the xor operator? You probably want to use binary and instead.

Something like this maybe?

if((DeviceInfo.getBatteryStatus() & DeviceInfo.BSTAT_IS_USING_EXTERNAL_POWER) != 0)
{
    // Plugged in
    // TODO : Do something
}else{
    // Not plugged in
    // TODO : Do something else
}