What is the best way to detect connection failure?
I know that we should use NetworkInfo.getState()
to get connection state,
and also I use BroadcastReceiver with NETWORK_STATE_CHANGED_ACTION
to detecting connection state changes.
I think that detecting DISCONNECTED
state in a broadcastReceiver is not match in this case.
NetworkInfo.State.DISCONNECTED
means only "disconnected", does not means connection fail.
Register the Receiver with WifiManager.SUPPLICANT_STATE_CHANGED_ACTION
to be notified when a connection failure occurs. It might be due to supplying invalid credentials for connecting to Wi-Fi.
private void registerReceiver() {
IntentFilter filter = new IntentFilter();
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
filter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
registerReceiver(mReceiver, filter);
}
And your Receiver below
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
}
}
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With