API 29中已弃用getActiveNetworkInfo() [英] getActiveNetworkInfo() is deprecated in API 29
问题描述
我正在使用一个代码检查用户是否已激活互联网,但是在定位了sdk29之后,以下功能就被弃用了
I am using a code that check if user has internet active or not but after targeting sdk29 the functions bellow became deprecated
NetworkInfo
NetworkInfo
NetworkInfo.isConnected()
NetworkInfo.isConnected()
getActiveNetworkInfo()
getActiveNetworkInfo()
这是代码:
public static boolean isNetworkAvailable(Context context) {
if(context == null) { return false; }
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
// if no network is available networkInfo will be null, otherwise check if we are connected
try {
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
if (activeNetworkInfo != null && activeNetworkInfo.isConnected()) {
Log.i("update_statut","Network is available : true");
return true;
}
} catch (Exception e) {
Log.i("update_statut",""+ e.getMessage());
}
Log.i("update_statut","Network is available : FALSE ");
return false;
}
推荐答案
我终于找到了可以在所有API上使用的代码,以防万一有人需要
I have finally found a code that works on all APIs in case anybody want it
NetworkCapabilities在API 29中并未被弃用,但它需要API 21,因此我仅在API 29上对其进行了调用.
NetworkCapabilities is not deprecated in API 29 but it requires API 21 so I have called it on API 29 only.
然而,仅在API 29中弃用了getActiveNetworkInfo(),并且只能在所有API上使用,因此我们可以在所有29以下的api中使用它
However getActiveNetworkInfo() is deprecated only in API 29 and works on all APIs , so we can use it in all apis bellow 29
这是代码
public static boolean isNetworkAvailable(Context context) {
if(context == null) return false;
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 if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)){
return true;
}
}
}
else {
try {
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
if (activeNetworkInfo != null && activeNetworkInfo.isConnected()) {
Log.i("update_statut", "Network is available : true");
return true;
}
} catch (Exception e) {
Log.i("update_statut", "" + e.getMessage());
}
}
}
Log.i("update_statut","Network is available : FALSE ");
return false;
}
这篇关于API 29中已弃用getActiveNetworkInfo()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!