how to check if wifi is really connected in Android

前端 未结 4 1070
一生所求
一生所求 2021-01-15 12:04

I\'d like my android device to connect to a wifi hotspot. I created a new wificonfiguration and add it into the wifimanager, this wificonfigu

4条回答
  •  我在风中等你
    2021-01-15 12:26

    You can check all the network. If you only want WIFI you can remove checking other 2 network.

    public static boolean hasInternetConnection()
    {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo wifiNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (wifiNetwork != null && wifiNetwork.isConnected())
        {
            return true;
        }
        NetworkInfo mobileNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        if (mobileNetwork != null && mobileNetwork.isConnected())
        {
            return true;
        }
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        if (activeNetwork != null && activeNetwork.isConnected())
        {
            return true;
        }
        return false;
    }
    

    Don't forget to add following in manifest:

    
    
    
    

提交回复
热议问题