How to detect when WIFI Connection has been established in Android?

前端 未结 13 727
庸人自扰
庸人自扰 2020-11-22 05:34

I need to detect when I have network connectivity over WIFI. What broadcast is sent to establish that a valid network connection has been made. I need to validate that a v

13条回答
  •  别跟我提以往
    2020-11-22 05:56

    You can register a BroadcastReceiver to be notified when a WiFi connection is established (or if the connection changed).

    Register the BroadcastReceiver:

    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
    registerReceiver(broadcastReceiver, intentFilter);
    

    And then in your BroadcastReceiver do something like this:

    @Override
    public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();
        if (action.equals(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION)) {
            if (intent.getBooleanExtra(WifiManager.EXTRA_SUPPLICANT_CONNECTED, false)) {
                //do stuff
            } else {
                // wifi connection was lost
            }
        }
    }
    

    For more info, see the documentation for BroadcastReceiver and WifiManager

    Of course you should check whether the device is already connected to WiFi before this.

    EDIT: Thanks to ban-geoengineering, here's a method to check whether the device is already connected:

    private boolean isConnectedViaWifi() {
         ConnectivityManager connectivityManager = (ConnectivityManager) appObj.getSystemService(Context.CONNECTIVITY_SERVICE);
         NetworkInfo mWifi = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);     
         return mWifi.isConnected();
    }
    

提交回复
热议问题