android 信号强度变化,android-监听wifi状态和信号强度变化
// /////////////////////////////////////////////////////////////////// 监听网络网络状态变化private MyReceiver mMyReceiver;private final String NETWORK_STATE_CHANGE = "android.net.conn.CONNECTIVITY_CHANGE";priva
// /
// 监听网络网络状态变化
private MyReceiver mMyReceiver;
private final String NETWORK_STATE_CHANGE = "android.net.conn.CONNECTIVITY_CHANGE";
private void registReceiver() {
if (mMyReceiver != null)
return;
mMyReceiver = new MyReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(NETWORK_STATE_CHANGE);
filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
filter.addAction(WifiManager.RSSI_CHANGED_ACTION);
registerReceiver(mMyReceiver, filter);
}
private void unregisterReceiver() {
if (mMyReceiver == null)
return;
unregisterReceiver(mMyReceiver);
mMyReceiver = null;
}
int[] wifiStateImgs = new int[] { R.drawable.selector_wifi_1,
R.drawable.selector_wifi_2, R.drawable.selector_wifi_3,
R.drawable.selector_wifi_4 };
private class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Logcat.d(TAG, "action: " + action);
if (action.equals(NETWORK_STATE_CHANGE)) {
boolean isNetOK = NetHelper
.isNetworkAvailable(MainActivity.this);
Logcat.d(TAG, "网络状态发生变化,是否可用:" + isNetOK);
if (isNetOK) {
initWifiState();
} else {
btnWifi.setBackgroundResource(R.drawable.selector_wifi_0);
}
} else if (action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
int wifistate = intent.getIntExtra(
WifiManager.EXTRA_WIFI_STATE,
WifiManager.WIFI_STATE_DISABLED);
if (wifistate == WifiManager.WIFI_STATE_DISABLED) {
btnWifi.setBackgroundResource(R.drawable.selector_wifi_0);
} else if (wifistate == WifiManager.WIFI_STATE_ENABLED) {
updateWifiStrength();
}
} else if (action.equals(WifiManager.RSSI_CHANGED_ACTION)) {
initWifiState();
}
}
}
public int getStrength(Context context) {
WifiManager wifiManager = (WifiManager) context
.getSystemService(Context.WIFI_SERVICE);
WifiInfo info = wifiManager.getConnectionInfo();
if (info.getBSSID() != null) {
int strength = WifiManager.calculateSignalLevel(info.getRssi(), 4);
// 链接速度
// int speed = info.getLinkSpeed();
// // 链接速度单位
// String units = WifiInfo.LINK_SPEED_UNITS;
// // Wifi源名称
// String ssid = info.getSSID();
return strength;
}
return 0;
}
public void initWifiState() {
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = manager
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
Logcat.d(TAG, "info.isConnected(): " + info.isConnected());
if (info.isConnected()) {
updateWifiStrength();
} else {
btnWifi.setBackgroundResource(R.drawable.selector_wifi_0);
}
}
public void updateWifiStrength() {
int strength = getStrength(this);
if (strength >= 0 && strength <= 3)
btnWifi.setBackgroundResource(wifiStateImgs[strength]);
Logcat.d(TAG, "wifi strength: " + strength);
}
更多推荐
所有评论(0)