Skip to content

Commit

Permalink
fix(connectivity_plus): Fix connectivity state update on Android when…
Browse files Browse the repository at this point in the history
… network is lost (#2673)
  • Loading branch information
vbuberen authored Mar 11, 2024
1 parent 915a443 commit 2119168
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 11 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionUrl=https\://services.gradle.org/distributions/gradle-7.6.1-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-bin.zip
distributionPath=wrapper/dists
zipStorePath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
Expand Down Expand Up @@ -48,9 +49,15 @@ public void onAvailable(Network network) {
sendEvent();
}

@Override
public void onCapabilitiesChanged(
Network network, NetworkCapabilities networkCapabilities) {
sendEvent();
}

@Override
public void onLost(Network network) {
sendEvent(Connectivity.CONNECTIVITY_NONE);
sendEvent();
}
};
connectivity.getConnectivityManager().registerDefaultNetworkCallback(networkCallback);
Expand All @@ -70,7 +77,7 @@ public void onCancel(Object arguments) {
try {
context.unregisterReceiver(this);
} catch (Exception e) {
//listen never called, ignore the error
// listen never called, ignore the error
}
}
}
Expand All @@ -84,11 +91,9 @@ public void onReceive(Context context, Intent intent) {

private void sendEvent() {
Runnable runnable = () -> events.success(connectivity.getNetworkTypes());
mainHandler.post(runnable);
}

private void sendEvent(final String networkType) {
Runnable runnable = () -> events.success(networkType);
mainHandler.post(runnable);
// The dalay is needed because callback methods suffer from race conditions.
// More info:
// https://developer.android.com/develop/connectivity/network-ops/reading-network-state#listening-events
mainHandler.postDelayed(runnable, 100);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,7 @@ class MethodChannelConnectivity extends ConnectivityPlatform {
Stream<List<ConnectivityResult>> get onConnectivityChanged {
_onConnectivityChanged ??= eventChannel
.receiveBroadcastStream()
.map((dynamic result) =>
result is String ? [result] : List<String>.from(result))
.map((dynamic result) => List<String>.from(result))
.map(parseConnectivityResults);
return _onConnectivityChanged!;
}
Expand Down

0 comments on commit 2119168

Please sign in to comment.