How do I see if Wi-Fi is connected on Android?

前端 未结 22 2627
挽巷
挽巷 2020-11-22 05:56

I don\'t want my user to even try downloading something unless they have Wi-Fi connected. However, I can only seem to be able to tell if Wi-Fi is enabled, but they could sti

22条回答
  •  误落风尘
    2020-11-22 06:09

    You should be able to use the ConnectivityManager to get the state of the Wi-Fi adapter. From there you can check if it is connected or even available.

    ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    
    if (mWifi.isConnected()) {
        // Do whatever
    }
    

    NOTE: It should be noted (for us n00bies here) that you need to add

    
    

    to your

    AndroidManifest.xml for this to work.

    NOTE2: public NetworkInfo getNetworkInfo (int networkType) is now deprecated:

    This method was deprecated in API level 23. This method does not support multiple connected networks of the same type. Use getAllNetworks() and getNetworkInfo(android.net.Network) instead.

    NOTE3: public static final int TYPE_WIFI is now deprecated:

    This constant was deprecated in API level 28. Applications should instead use NetworkCapabilities.hasTransport(int) or requestNetwork(NetworkRequest, NetworkCallback) to request an appropriate network. for supported transports.

提交回复
热议问题