📅  最后修改于: 2023-12-03 15:17:51.476000             🧑  作者: Mango
The NetworkInfo
class in Android has been deprecated since API level 29. This means that it is no longer recommended to use this class for network connectivity checks in your Android applications. In this guide, we will explore the deprecation, understand the reasons behind it, and learn about the alternative approaches.
The deprecation of NetworkInfo
is a result of the introduction of a more modern and reliable connectivity management system in Android. With the release of Android 10 (API level 29) and above, the Android team introduced the NetworkCapabilities and ConnectivityManager.NetworkCallback classes to handle network connectivity.
You can use the NetworkCapabilities
class to check for network capabilities such as Internet connectivity, bandwidth, and transport type.
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkCapabilities networkCapabilities = connectivityManager.getNetworkCapabilities(connectivityManager.getActiveNetwork());
boolean isConnected = networkCapabilities != null && networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
To receive notifications about network changes, you can register a NetworkCallback
with the ConnectivityManager
.
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback() {
@Override
public void onAvailable(Network network) {
// network available
}
@Override
public void onLost(Network network) {
// network lost
}
};
connectivityManager.registerDefaultNetworkCallback(networkCallback);
Here are the steps to migrate from using NetworkInfo
to the recommended approaches:
NetworkInfo
class.NetworkCapabilities
as shown in the first approach.NetworkCallback
registration as shown in the second approach.In conclusion, the NetworkInfo
class has been deprecated and replaced with more modern and reliable approaches like NetworkCapabilities
and NetworkCallback
. It is essential to update your code to utilize these new classes for handling network connectivity in Android applications.
Remember to update your code and migrate to the recommended approaches to ensure compatibility with the latest Android versions and provide a better user experience.
Note: The code snippets provided in this guide are written in Java. If you are using Kotlin, it is recommended to convert the code to Kotlin syntax.