Skip to content

Commit

Permalink
fix(android): populate network value during initial module startup (#553
Browse files Browse the repository at this point in the history
)

- Make sure the callback is called at least once on register so starting the app 
  with no connectivity reports it as none instead of unknown.

- Replace Runnable with lambda as suggested by linter
  • Loading branch information
cristianoccazinsp committed Dec 20, 2021
1 parent e342e26 commit c05080f
Showing 1 changed file with 15 additions and 10 deletions.
Expand Up @@ -54,6 +54,14 @@ public NetworkCallbackConnectivityReceiver(ReactApplicationContext reactContext)
public void register() {
try {
NetworkRequest.Builder builder = new NetworkRequest.Builder();

// Similar to BroadcastReceiver implementation, we need to force
// an initial callback call in order to get the current network state,
// otherwise, an app started without any network connection will
// always be reported as "unknown".
mNetwork = getConnectivityManager().getActiveNetwork();
asyncUpdateAndSend(0);

getConnectivityManager().registerNetworkCallback(builder.build(), mNetworkCallback);
} catch (SecurityException e) {
// TODO: Display a yellow box about this
Expand Down Expand Up @@ -131,22 +139,19 @@ void updateAndSend() {
updateConnectivity(connectionType, cellularGeneration, isInternetReachable);
}

private void asyncUpdateAndSend() {
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
@Override
public void run() {
mCapabilities = getConnectivityManager().getNetworkCapabilities(mNetwork);
updateAndSend();
private void asyncUpdateAndSend(int delay) {
new Handler(Looper.getMainLooper()).postDelayed(() -> {
mCapabilities = getConnectivityManager().getNetworkCapabilities(mNetwork);
updateAndSend();

}
}, DELAY_MS);
}, delay);
}

private class ConnectivityNetworkCallback extends ConnectivityManager.NetworkCallback {
@Override
public void onAvailable(Network network) {
mNetwork = network;
asyncUpdateAndSend();
asyncUpdateAndSend(DELAY_MS);
}

@Override
Expand Down Expand Up @@ -182,7 +187,7 @@ public void onLinkPropertiesChanged(Network network, LinkProperties linkProperti
if (mNetwork != null) {
mNetwork = network;
}
asyncUpdateAndSend();
asyncUpdateAndSend(DELAY_MS);
}
}
}

0 comments on commit c05080f

Please sign in to comment.