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

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

    I have two methods to detect WIFI connection receiving the application context:

    1)my old method

    public boolean isConnectedWifi1(Context context) {
        try {
            ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();           
            if (networkInfo != null) {
                NetworkInfo[] netInfo = connectivityManager.getAllNetworkInfo();
                for (NetworkInfo ni : netInfo) {
                    if ((ni.getTypeName().equalsIgnoreCase("WIFI"))
                            && ni.isConnected()) {
                        return true;
                    }                   
                }
            }
            return false;
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }
        return false;
    }
    

    2)my New method (I´m currently using this method):

    public boolean isConnectedWifi(Context context) {
             ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
             NetworkInfo networkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);     
             return networkInfo.isConnected();
    }
    

提交回复
热议问题