使用 compileSdkVersion 23 ,但试图支持早至 9。
getNetworkInfo(int)在 23 中已弃用。建议使用getAllNetworks()andgetNetworkInfo(Network)代替。但是,这两者都需要至少 API 21。
getNetworkInfo(int)
getAllNetworks()
getNetworkInfo(Network)
是否有我们可以在支持包中使用的类来帮助解决这个问题?
您可以使用:
获取活动网络信息();
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); if (activeNetwork != null) { // connected to the internet if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) { // connected to wifi } else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) { // connected to mobile data } } else { // not connected to the internet }
或者在开关盒中
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); if (activeNetwork != null) { // connected to the internet switch (activeNetwork.getType()) { case ConnectivityManager.TYPE_WIFI: // connected to wifi break; case ConnectivityManager.TYPE_MOBILE: // connected to mobile data break; default: break; } } else { // not connected to the internet }