我不希望我的用户尝试下载任何东西,除非他们连接了Wi-Fi。然而,我似乎只能判断是否启用了Wi-Fi,但他们仍然可能有3G连接。
android.net.wifi.WifiManager m = (WifiManager) getSystemService(WIFI_SERVICE);
android.net.wifi.SupplicantState s = m.getConnectionInfo().getSupplicantState();
NetworkInfo.DetailedState state = WifiInfo.getDetailedStateOf(s);
if (state != NetworkInfo.DetailedState.CONNECTED) {
return false;
}
然而,这种状态并不是我所期望的。即使Wi-Fi是连接的,我得到OBTAINING_IPADDR作为状态。
这个问题有点老了,但我用的就是这个。要求最低api级别21也考虑到废弃的Networkinfo api。
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;