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

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

    Kind of old a question but this is what i use. requires min api level 21 also takes in consideration deprecated Networkinfo apis.

    boolean isWifiConn = false;
        ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            Network network = connMgr.getActiveNetwork();
            if (network == null) return false;
            NetworkCapabilities capabilities = connMgr.getNetworkCapabilities(network);
            if(capabilities != null && capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)){
                isWifiConn = true;
                Toast.makeText(context,"Wifi connected Api >= "+Build.VERSION_CODES.M,Toast.LENGTH_LONG).show();
            }else{
                Toast.makeText(context,"Wifi not connected Api >= "+Build.VERSION_CODES.M,Toast.LENGTH_LONG).show();
            }
        } else {
            for (Network network : connMgr.getAllNetworks()) {
                NetworkInfo networkInfo = connMgr.getNetworkInfo(network);
                if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI && networkInfo.isConnected()) {
                    isWifiConn = true;
                    Toast.makeText(context,"Wifi connected ",Toast.LENGTH_LONG).show();
                    break;
                }else{
                    Toast.makeText(context,"Wifi not connected ",Toast.LENGTH_LONG).show();
                }
            }
        }
        return isWifiConn;
    

提交回复
热议问题