我想获得与我的设备连接的这个wifi的信号强度.这可能很容易.但我是初学者.这是家庭作业.怎么弄?
我试过这段代码.但它不起作用.
registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
int state = wifi.getWifiState();
if(state == WifiManager.WIFI_STATE_ENABLED) {
List results = wifi.getScanResults();
for (ScanResult result : results) {
if(result.BSSID.equals(wifi.getConnectionInfo().getBSSID())) {
int level = WifiManager.calculateSignalLevel(wifi.getConnectionInfo().getRssi(),
result.level);
int difference = level * 100 / result.level;
int signalStrangth= 0;
if(difference >= 100)
signalStrangth = 4;
else if(difference >= 75)
signalStrangth = 3;
else if(difference >= 50)
signalStrangth = 2;
else if(difference >= 25)
signalStrangth = 1;
tv.setText(tv.getText() + "\nDifference :" + difference + " signal state:" + signalStrangth);
}
}
}
}
}, new IntentFilter(WifiManager.RSSI_CHANGED_ACTION));
我也试过这段代码.但这也行不通.
int numberOfLevels = 5;
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int level = WifiManager.calculateSignalLevel(wifiInfo.getRssi(), numberOfLevels);