似乎整个 NetworkInfo在 API 29 上已被弃用。
所以我正在寻找一种替代方法来检查网络是否已连接。例如替代
connectivityManager.activeNetworkInfo?.isConnected == true
旁注:我知道现在有一个回调,但我想同步获取此信息。此外,我当然知道它可能不是一个精确的信息,尽管我想拥有它。
似乎整个 NetworkInfo在 API 29 上已被弃用。
所以我正在寻找一种替代方法来检查网络是否已连接。例如替代
connectivityManager.activeNetworkInfo?.isConnected == true
旁注:我知道现在有一个回调,但我想同步获取此信息。此外,我当然知道它可能不是一个精确的信息,尽管我想拥有它。
解决方案是这样的:
val capability = connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork)
return capability?.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) ?: false
这适用于 API 29:
connectivityManager.isDefaultNetworkActive
android.net.NetworkInfo
此类在 API 级别 29 中已弃用。您应该改为使用ConnectivityManager.NetworkCallback
API 来了解连接更改
参考链接https://developer.android.com/reference/android/net/NetworkInfo.html
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkRequest.Builder builder = new NetworkRequest.Builder();
connectivityManager.registerNetworkCallback(
builder.build(),
new ConnectivityManager.NetworkCallback() {
@Override
public void onAvailable(Network network) {
// Network Available
}
@Override
public void onLost(Network network) {
// Network Not Available
}
}
);
解决方案是
public void registerNetworkCallback()
{
try {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkRequest.Builder builder = new NetworkRequest.Builder();
connectivityManager.registerNetworkCallback(builder.build(),new ConnectivityManager.NetworkCallback() {
@Override
public void onAvailable(Network network) {
Variables.isNetworkConnected = true; // Global Static Variable
}
@Override
public void onLost(Network network) {
Variables.isNetworkConnected = false; // Global Static Variable
}
}
);
Variables.isNetworkConnected = false;
}catch (Exception e){
Variables.isNetworkConnected = false;
}
}
在此处查看完整代码:要点
private boolean checkInternetConnection(Activity activity) {
ConnectivityManager connectivityManager = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
Network network = null;
if (connectivityManager == null) {
return false;
} else {
network = connectivityManager.getActiveNetwork();
NetworkCapabilities networkCapabilities = connectivityManager.getNetworkCapabilities(network);
if (networkCapabilities == null) {
return false;
}
if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) ||
networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
return true;
}
}
} else {
if (connectivityManager == null) {
return false;
}
if (connectivityManager.getActiveNetworkInfo() == null) {
return false;
}
return connectivityManager.getActiveNetworkInfo().isConnected();
}
return false;
}