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

前端 未结 13 720
庸人自扰
庸人自扰 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:50

    Here is an example of my code, that takes into account the users preference of only allowing comms when connected to Wifi.

    I am calling this code from inside an IntentService before I attempt to download stuff.

    Note that NetworkInfo will be null if there is no network connection of any kind.

    private boolean canConnect()
    {
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    
        boolean canConnect = false;
        boolean wifiOnly = SharedPreferencesUtils.wifiOnly();
    
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if(networkInfo != null)
        {
            if(networkInfo.isConnected())
            {
                if((networkInfo.getType() == ConnectivityManager.TYPE_WIFI) ||
                   (networkInfo.getType() != ConnectivityManager.TYPE_WIFI && !wifiOnly))
                {
                    canConnect = true;
                }
            }
        }
    
        return canConnect;
    }
    

提交回复
热议问题