检测连接失败的最佳方法是什么?
我知道我们应该NetworkInfo.getState()
用来获取连接状态,并且我也可以使用BroadcastReceiver NETWORK_STATE_CHANGED_ACTION
来检测连接状态的变化。
我认为DISCONNECTED
在这种情况下,在broadcastReceiver 中检测状态不匹配。
NetworkInfo.State.DISCONNECTED
表示仅“断开连接”,并不表示连接失败。
向接收器注册WifiManager.SUPPLICANT_STATE_CHANGED_ACTION
以在发生连接故障时收到通知。可能是由于提供无效的凭据以连接到Wi-Fi。
private void registerReceiver() { IntentFilter filter = new IntentFilter(); filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); filter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION); registerReceiver(mReceiver, filter); }
还有您的接收器
private BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO); if (info != null) { if (info.isConnected()) { //connected WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); WifiInfo wifiInfo = wifiManager.getConnectionInfo(); String ssid = wifiInfo.getSSID(); } } else { if (intent.getAction().equals(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION)) { if (intent.hasExtra(WifiManager.EXTRA_SUPPLICANT_ERROR)) { //failed to connect } } } };