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

前端 未结 22 2626
挽巷
挽巷 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:11

    Since the method NetworkInfo.isConnected() is now deprecated in API-23, here is a method which detects if the Wi-Fi adapter is on and also connected to an access point using WifiManager instead:

    private boolean checkWifiOnAndConnected() {
        WifiManager wifiMgr = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    
        if (wifiMgr.isWifiEnabled()) { // Wi-Fi adapter is ON
    
            WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
    
            if( wifiInfo.getNetworkId() == -1 ){
                return false; // Not connected to an access point
            }
            return true; // Connected to an access point
        }
        else {
            return false; // Wi-Fi adapter is OFF
        }
    }
    

提交回复
热议问题