NetworkUtils { public static boolean isConnected(Context context) { ConnectivityManager manager = ContextCompat.getSystemService(context, ConnectivityManager.class); if (manager == null) { return false; } if (Build.VERSION.SDK_INT < 29) { NetworkInfo networkInfo = manager.getActiveNetworkInfo(); return (networkInfo != null && networkInfo.isConnected()); } else { Network network = manager.getActiveNetwork(); NetworkCapabilities capabilities = manager.getNetworkCapabilities(network); if (capabilities != null) { return capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET); } else { return false; } } }  static boolean isConnected(Context context); static boolean isMeteredConnection(Context context); static void maybeLaunchBrowser(Context context, String url); static void maybeLaunchIntent(Context context, Intent intent);  }
@Test @SuppressWarnings("deprecation") public void testIsConnected() { Context context = mock(Context.class); ConnectivityManager manager = mock(ConnectivityManager.class); when(context.getSystemService(Context.CONNECTIVITY_SERVICE)).thenReturn(manager); if (Build.VERSION.SDK_INT < 29) { NetworkInfo networkInfo = mock(NetworkInfo.class); when(manager.getActiveNetworkInfo()).thenReturn(networkInfo); when(networkInfo.isConnected()).thenReturn(true); assertTrue(NetworkUtils.isConnected(context)); when(networkInfo.isConnected()).thenReturn(false); assertFalse(NetworkUtils.isConnected(context)); } else { when(manager.getActiveNetwork()).thenReturn(null); assertFalse(NetworkUtils.isConnected(context)); Network network = mock(Network.class); NetworkCapabilities capabilities = mock(NetworkCapabilities.class); when(manager.getActiveNetwork()).thenReturn(network); when(manager.getNetworkCapabilities(network)).thenReturn(capabilities); assertFalse(NetworkUtils.isConnected(context)); when(capabilities.hasCapability(any())).thenReturn(true); assertTrue(NetworkUtils.isConnected(context)); } }