Skip to content

Commit

Permalink
Adding suggested changes
Browse files Browse the repository at this point in the history
1. Using `connectivityManager.getNetworkCapabilities` instead of `networkRequest.hasCapability` which was giving incorrect values before.
2. ConnectivityManager is now global private variable.
3. Logic of checking initial state of connectivity is modularized and moved to constructor.
  • Loading branch information
“Akshay committed Nov 16, 2022
1 parent d9526b6 commit e2fe72c
Showing 1 changed file with 14 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,10 @@

class IterableNetworkConnectivityManager {
private static final String TAG = "NetworkConnectivityManager";
private boolean isConnected = true;
private boolean isConnected;

private static IterableNetworkConnectivityManager sharedInstance;

private ConnectivityManager connectivityManager;
private ArrayList<IterableNetworkMonitorListener> networkMonitorListeners = new ArrayList<>();
private Set<Network> networkSet = new HashSet<>();

Expand All @@ -41,17 +41,25 @@ private IterableNetworkConnectivityManager(Context context) {
return;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
checkInternetAvailabilityOnActiveNetwork();
startNetworkCallback(context);
}
}

private void checkInternetAvailabilityOnActiveNetwork() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
Network activeNetwork = connectivityManager.getActiveNetwork();
isConnected = connectivityManager.getNetworkCapabilities(activeNetwork).hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
IterableLogger.v(TAG, "Network connection status " + isConnected);
} else {
IterableLogger.v(TAG, "Internet capability could not be detected on active network due to Android OS < Marshmallow.");
}
}

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void startNetworkCallback(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkRequest networkRequest = new NetworkRequest.Builder().build();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
isConnected = networkRequest.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
}
if (connectivityManager != null) {
try {
connectivityManager.registerNetworkCallback(networkRequest, new ConnectivityManager.NetworkCallback() {
Expand Down

0 comments on commit e2fe72c

Please sign in to comment.