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

前端 未结 13 969
庸人自扰
庸人自扰 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 06:14

    This code does not require permission at all. It is restricted only to Wi-Fi network connectivity state changes (any other network is not taken into account). The receiver is statically published in the AndroidManifest.xml file and does not need to be exported as it will be invoked by the system protected broadcast, NETWORK_STATE_CHANGED_ACTION, at every network connectivity state change.

    AndroidManifest:

    
    
        
            
            
            
        
    
    
    

    BroadcastReceiver class:

    public class WifiReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
    /*
     Tested (I didn't test with the WPS "Wi-Fi Protected Setup" standard):
     In API15 (ICE_CREAM_SANDWICH) this method is called when the new Wi-Fi network state is:
     DISCONNECTED, OBTAINING_IPADDR, CONNECTED or SCANNING
    
     In API19 (KITKAT) this method is called when the new Wi-Fi network state is:
     DISCONNECTED (twice), OBTAINING_IPADDR, VERIFYING_POOR_LINK, CAPTIVE_PORTAL_CHECK
     or CONNECTED
    
     (Those states can be obtained as NetworkInfo.DetailedState objects by calling
     the NetworkInfo object method: "networkInfo.getDetailedState()")
    */
        /*
         * NetworkInfo object associated with the Wi-Fi network.
         * It won't be null when "android.net.wifi.STATE_CHANGE" action intent arrives.
         */
        NetworkInfo networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
    
        if (networkInfo != null && networkInfo.isConnected()) {
            // TODO: Place the work here, like retrieving the access point's SSID
    
            /*
             * WifiInfo object giving information about the access point we are connected to.
             * It shouldn't be null when the new Wi-Fi network state is CONNECTED, but it got
             * null sometimes when connecting to a "virtualized Wi-Fi router" in API15.
             */
            WifiInfo wifiInfo = intent.getParcelableExtra(WifiManager.EXTRA_WIFI_INFO);
            String ssid = wifiInfo.getSSID();
        }
    }
    }
    

    Permissions:

    None
    

提交回复
热议问题