Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I detect fail to connect wifi in android?

Tags:

android

wifi

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.

like image 901
user3752013 Avatar asked Mar 15 '23 00:03

user3752013


1 Answers

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
                }
            }
        }
    };
like image 190
Anoop M Maddasseri Avatar answered Apr 02 '23 06:04

Anoop M Maddasseri