Try this if you need
- register to the network state changes
- consider all network interfaces
- want to be notified if network is available for any interface
- that code supports API>20 (you can add also legacy API support easily)
Declare the necessary variables in your class:
private static final HashMap<Network, Boolean> mNetworkStates = new HashMap<>();
private final Object mSyncNetworkState = new Object();
private Boolean mNetworkState;
Define your method which monitors the interface changes. mNetworkState shows always if at least one network interface is connected.
private void registerNetworkStateInfo(@NonNull final Context context) throws Exception {
final ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkRequest.Builder builder = new NetworkRequest.Builder();
if (connectivityManager != null) {
connectivityManager.registerNetworkCallback(
builder.build(),
new ConnectivityManager.NetworkCallback() {
@Override
public void onAvailable(@NonNull Network network) {
mNetworkStates.put(network, true);
synchronized (mSyncNetworkState){
mNetworkState = true;
}
Log.d("Network state", "Network state: true");
}
@Override
public void onLost(@NonNull Network network) {
mNetworkStates.put(network, false);
synchronized (mSyncNetworkState){
mNetworkState = false;
Log.d("Network state", "Network state: false");
mNetworkStates.forEach(new BiConsumer<Network, Boolean>() {
@Override
public void accept(Network nextNetwork, Boolean state) {
if (state.equals(true)) {
mNetworkState= true;
Log.d("Network state", "Network state: but true");
}
}
});
}
}
}
);
} else {
synchronized (mSyncNetworkState){
mNetworkState = false;
}
throw new Exception("Connectivity Manager is not available");
}
}
Use your mNetworkState
synchronized (mSyncNetworkState){
if (!mNetworkState) {
throw new Exception("No network available");
}
}