在我的Android应用程序中,我使用以下两种方法来检查设备是否已连接到WiFi以及通常是否可以使用网络连接。我假设当设备连接到WiFi或移动网络时,也可以使用互联网。
public static boolean wifiConnected(Context context) {
boolean isWifiConn = false;
ConnectivityManager connMgr = (ConnectivityManager) context.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
android.net.Network network = connMgr.getActiveNetwork();
if (network == null) return false;
NetworkCapabilities capabilities = connMgr.getNetworkCapabilities(network);
if(capabilities != null && capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)){
isWifiConn = true;
}
} else {
for (android.net.Network network : connMgr.getAllNetworks()) {
NetworkInfo networkInfo = connMgr.getNetworkInfo(network);
if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI && networkInfo.isConnected()) {
isWifiConn = true;
break;
}
}
}
return isWifiConn;
}
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager
= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null) {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(connectivityManager.getActiveNetwork());
if (capabilities != null) {
if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
return true;
} else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
return true;
} else return capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET);
}
} else {
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return (activeNetworkInfo != null) && activeNetworkInfo.isConnected();
}
}
return false;
}
如果设备通过VPN连接,则方法返回false。是否可以扩展这些方法,以便即使将设备连接到VPN时也能返回true?
答案 0 :(得分:0)
VPN有特定的传输类型,因此您要做的就是添加对capabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN)
的检查。
您还可以将API级别检查从Build.VERSION_CODES.Q
更改为Build.VERSION_CODES.M
。唯一有问题的行是connectivityManager.getActiveNetwork()
,但这在M(API 23)中可用。