Junior — Middle
How can the availability of a network connection be determined?
sobes.tech AI
Answer from AI
In Android, the ConnectivityManager class is usually used to determine network connectivity. It helps to check whether there is an active network connection and what type it is (Wi-Fi, mobile data, etc.).
Example of checking network availability:
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
Starting from Android API 29, it is recommended to use NetworkCapabilities via ConnectivityManager:
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
Network network = cm.getActiveNetwork();
NetworkCapabilities capabilities = cm.getNetworkCapabilities(network);
boolean hasInternet = capabilities != null && capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);