Android2.2中WifiManager.calculateSignalLevel函数的BUG

android.net.wifi.WifiManager.calculateSignalLevel(int rssi, int numLevels) 当传递的numLevels的值大于等于46的时候,会出现除数为0的错误。

该函数在Android2.2 sdk中的实现如下

    public static int calculateSignalLevel(int rssi, int numLevels) {
        if (rssi <= MIN_RSSI) {
            return 0;
        } else if (rssi >= MAX_RSSI) {
            return numLevels - 1;
        } else {
            int partitionSize = (MAX_RSSI - MIN_RSSI) / (numLevels - 1);//当numLevels > 46时,partitionSize = (-55 - -100) / (46 - 1) = 0
            return (rssi - MIN_RSSI) / partitionSize;//错误:除数为0
        }
    }

可以自己实现该函数从而避免这一BUG:

    public static int calculateSignalLevel(int rssi, int numLevels){
		
	    int MIN_RSSI        = -100;
	    int MAX_RSSI        = -55;  
	    int levels          = 101;

        
        if (rssi <= MIN_RSSI) {
            return 0;
        } else if (rssi >= MAX_RSSI) {
            return levels - 1;
        } else {
            float inputRange = (MAX_RSSI - MIN_RSSI);
            float outputRange = (levels - 1);
            return (int)((float)(rssi - MIN_RSSI) * outputRange / inputRange);
        }	
    }

参考:

http://code.google.com/p/android/issues/detail?id=2555

http://stackoverflow.com/questions/2873469/issue-with-wifimanager-calculatesignallevelrssi-5


你可能感兴趣的:(android,float)