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

前端 未结 22 2910
挽巷
挽巷 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

    In new version Android

    private void getWifiInfo(Context context) {
        ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        Network[] networks = connManager.getAllNetworks();
    
        if(networks == null || networks.length == 0)
            return;
    
        for( int i = 0; i < networks.length; i++) {
            Network ntk = networks[i];
            NetworkInfo ntkInfo = connManager.getNetworkInfo(ntk);
            if (ntkInfo.getType() == ConnectivityManager.TYPE_WIFI && ntkInfo.isConnected() ) {
                final WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
                final WifiInfo connectionInfo = wifiManager.getConnectionInfo();
                if (connectionInfo != null) {
                    // add some code here
                }
            }
    
        }
    }
    

    and add premission too

提交回复
热议问题