我不希望我的用户尝试下载任何东西,除非他们连接了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作为状态。
这适用于最新版本的android:
fun getConnectionType(context: Context): ConnectivityType {
var result = NONE
val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (cm != null) {
val capabilities = cm.getNetworkCapabilities(cm.activeNetwork)
if (capabilities != null) {
when {
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> {
result = WIFI
}
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> {
result = MOBILE_DATA
}
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN) -> {
result = VPN
}
}
}
}
} else {
if (cm != null) {
val activeNetwork = cm.activeNetworkInfo
if (activeNetwork != null) {
// connected to the internet
when (activeNetwork.type) {
ConnectivityManager.TYPE_WIFI -> {
result = WIFI
}
ConnectivityManager.TYPE_MOBILE -> {
result = MOBILE_DATA
}
ConnectivityManager.TYPE_VPN -> {
result = VPN
}
}
}
}
}
return result
}
enum class ConnectivityType {
NONE,
MOBILE_DATA,
WIFI,
VPN,
}
在清单中:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
这对我来说很管用:
ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
// Mobile
State mobile = conMan.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
// Wi-Fi
State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
// And then use it like this:
if (mobile == NetworkInfo.State.CONNECTED || mobile == NetworkInfo.State.CONNECTING)
{
Toast.makeText(Wifi_Gprs.this,"Mobile is Enabled :) ....",Toast.LENGTH_LONG).show();
}
else if (wifi == NetworkInfo.State.CONNECTED || wifi == NetworkInfo.State.CONNECTING)
{
Toast.makeText(Wifi_Gprs.this,"Wifi is Enabled :) ....",Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(Wifi_Gprs.this,"No Wifi or Gprs Enabled :( ....",Toast.LENGTH_LONG).show();
}
并添加以下权限:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />