Java Code Examples for android.net.ConnectivityManager#NetworkCallback

The following examples show how to use android.net.ConnectivityManager#NetworkCallback . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AirplaneModeAndroidTest.java    From firebase-jobdispatcher-android with Apache License 2.0 6 votes vote down vote up
private void waitForSomeNetworkToConnect() throws Exception {
  final SettableFuture<Void> future = SettableFuture.create();

  ConnectivityManager.NetworkCallback cb =
      new ConnectivityManager.NetworkCallback() {
        @Override
        public void onAvailable(Network network) {
          NetworkInfo netInfo = connManager.getNetworkInfo(network);
          if (netInfo != null && netInfo.isConnected()) {
            future.set(null);
          }
        }
      };

  connManager.requestNetwork(
      new NetworkRequest.Builder().addCapability(NET_CAPABILITY_INTERNET).build(), cb);

  try {
    future.get(NETWORK_STATE_CHANGE_TIMEOUT_SECONDS, TimeUnit.SECONDS);
  } finally {
    connManager.unregisterNetworkCallback(cb);
  }
}
 
Example 2
Source File: AndroidChannelBuilderTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Implementation(minSdk = LOLLIPOP)
@Override
public void unregisterNetworkCallback(ConnectivityManager.NetworkCallback networkCallback) {
  if (getApiLevel() >= N) {
    if (networkCallback != null || defaultNetworkCallbacks.contains(networkCallback)) {
      defaultNetworkCallbacks.remove(networkCallback);
    }
  }
  super.unregisterNetworkCallback(networkCallback);
}
 
Example 3
Source File: MultipathPolicyTracker.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private void registerTrackMobileCallback() {
    final NetworkRequest request = new NetworkRequest.Builder()
            .addCapability(NET_CAPABILITY_INTERNET)
            .addTransportType(TRANSPORT_CELLULAR)
            .build();
    mMobileNetworkCallback = new ConnectivityManager.NetworkCallback() {
        @Override
        public void onCapabilitiesChanged(Network network, NetworkCapabilities nc) {
            MultipathTracker existing = mMultipathTrackers.get(network);
            if (existing != null) {
                existing.setNetworkCapabilities(nc);
                existing.updateMultipathBudget();
                return;
            }

            try {
                mMultipathTrackers.put(network, new MultipathTracker(network, nc));
            } catch (IllegalStateException e) {
                Slog.e(TAG, "Can't track mobile network " + network + ": " + e.getMessage());
            }
            if (DBG) Slog.d(TAG, "Tracking mobile network " + network);
        }

        @Override
        public void onLost(Network network) {
            MultipathTracker existing = mMultipathTrackers.get(network);
            if (existing != null) {
                existing.shutdown();
                mMultipathTrackers.remove(network);
            }
            if (DBG) Slog.d(TAG, "No longer tracking mobile network " + network);
        }
    };

    mCM.registerNetworkCallback(request, mMobileNetworkCallback, mHandler);
}
 
Example 4
Source File: ESPDevice.java    From esp-idf-provisioning-android with Apache License 2.0 5 votes vote down vote up
@RequiresPermission(Manifest.permission.ACCESS_NETWORK_STATE)
private void enableOnlyWifiNetwork() {

    Log.d(TAG, "enableOnlyWifiNetwork()");

    NetworkRequest.Builder request = new NetworkRequest.Builder();
    request.addTransportType(NetworkCapabilities.TRANSPORT_WIFI);

    networkCallback = new ConnectivityManager.NetworkCallback() {

        @Override
        public void onAvailable(Network network) {

            Log.e(TAG, "Network is available - 3");
            connectivityManager.bindProcessToNetwork(network);
        }

        @Override
        public void onUnavailable() {
            super.onUnavailable();
            Log.e(TAG, "Network is Unavailable - 3");
        }

        @Override
        public void onLost(@NonNull Network network) {
            super.onLost(network);
            Log.e(TAG, "Lost Network Connection - 3");
        }
    };
    connectivityManager.registerNetworkCallback(request.build(), networkCallback);
}
 
Example 5
Source File: FadeInNetworkImageView.java    From QuickLyric with GNU General Public License v3.0 5 votes vote down vote up
@TargetApi(21)
@Override
public void setImageUrl(String url, ImageLoader imageLoader) {
    mShowLocal = TextUtils.isEmpty(url);
    if (mDiskCache.get(url) == null && !OnlineAccessVerifier.check(getContext())) {
        this.setImageBitmap(null);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            final ConnectivityManager cm = (ConnectivityManager)
                    getContext().getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
            networkCallback = new ConnectivityManager.NetworkCallback() {
                @Override
                public void onAvailable(Network network) {
                    super.onAvailable(network);
                    new CoverArtLoader((MainActivity) FadeInNetworkImageView.this.getActivity()).execute(mLyrics);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && networkCallback != null)
                        try {
                            cm.unregisterNetworkCallback(networkCallback);
                        } catch (IllegalArgumentException ignored) {
                        }
                }
            };
            NetworkRequest request = new NetworkRequest.Builder()
                    .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).build();
            cm.registerNetworkCallback(request, networkCallback);
        }
        defaultShown = true;
    } else {
        super.setImageUrl(url, imageLoader);
        if (!TextUtils.isEmpty(url))
            defaultShown = false;
    }
}
 
Example 6
Source File: AndroidChannelBuilderTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Implementation(minSdk = LOLLIPOP)
@Override
public void unregisterNetworkCallback(ConnectivityManager.NetworkCallback networkCallback) {
  if (getApiLevel() >= N) {
    if (networkCallback != null || defaultNetworkCallbacks.contains(networkCallback)) {
      defaultNetworkCallbacks.remove(networkCallback);
    }
  }
  super.unregisterNetworkCallback(networkCallback);
}
 
Example 7
Source File: AndroidChannelBuilderTest.java    From grpc-nebula-java with Apache License 2.0 4 votes vote down vote up
private void notifyDefaultNetworkCallbacksOnAvailable(Network network) {
  for (ConnectivityManager.NetworkCallback networkCallback : defaultNetworkCallbacks) {
    networkCallback.onAvailable(network);
  }
}
 
Example 8
Source File: AndroidChannelBuilderTest.java    From grpc-nebula-java with Apache License 2.0 4 votes vote down vote up
private void notifyDefaultNetworkCallbacksOnLost(Network network) {
  for (ConnectivityManager.NetworkCallback networkCallback : defaultNetworkCallbacks) {
    networkCallback.onLost(network);
  }
}
 
Example 9
Source File: AndroidChannelBuilderTest.java    From grpc-nebula-java with Apache License 2.0 4 votes vote down vote up
@Implementation(minSdk = N)
protected void registerDefaultNetworkCallback(
    ConnectivityManager.NetworkCallback networkCallback) {
  defaultNetworkCallbacks.add(networkCallback);
}
 
Example 10
Source File: MainActivity.java    From wear-os-samples with Apache License 2.0 4 votes vote down vote up
private void requestHighBandwidthNetwork() {
    // Before requesting a high-bandwidth network, ensure prior requests are invalidated.
    unregisterNetworkCallback();

    Log.d(LOG_TAG, "Requesting high-bandwidth network");

    // Requesting an unmetered network may prevent you from connecting to the cellular
    // network on the user's watch or phone; however, unless you explicitly ask for permission
    // to a access the user's cellular network, you should request an unmetered network.
    NetworkRequest request = new NetworkRequest.Builder()
            .addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)
            .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
            .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
            .addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
            .build();

    mNetworkCallback = new ConnectivityManager.NetworkCallback() {
        @Override
        public void onAvailable(final Network network) {
            mTimeOutHandler.removeMessages(MESSAGE_CONNECTIVITY_TIMEOUT);

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    // requires android.permission.INTERNET
                    if (!mConnectivityManager.bindProcessToNetwork(network)) {
                        Log.e(LOG_TAG, "ConnectivityManager.bindProcessToNetwork()"
                                + " requires android.permission.INTERNET");
                        setUiState(UI_STATE_REQUEST_NETWORK);
                    } else {
                        Log.d(LOG_TAG, "Network available");
                        setUiState(UI_STATE_NETWORK_CONNECTED);
                    }
                }
            });
        }

        @Override
        public void onCapabilitiesChanged(Network network,
                                          NetworkCapabilities networkCapabilities) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Log.d(LOG_TAG, "Network capabilities changed");
                }
            });
        }

        @Override
        public void onLost(Network network) {
            Log.d(LOG_TAG, "Network lost");

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    setUiState(UI_STATE_REQUEST_NETWORK);
                }
            });
        }
    };

    // requires android.permission.CHANGE_NETWORK_STATE
    mConnectivityManager.requestNetwork(request, mNetworkCallback);

    mTimeOutHandler.sendMessageDelayed(
            mTimeOutHandler.obtainMessage(MESSAGE_CONNECTIVITY_TIMEOUT),
            NETWORK_CONNECTIVITY_TIMEOUT_MS);
}
 
Example 11
Source File: ConnectorUtils.java    From WifiUtils with Apache License 2.0 4 votes vote down vote up
@RequiresApi(Build.VERSION_CODES.Q)
private static boolean connectAndroidQ(@Nullable ConnectivityManager connectivityManager, @NonNull ScanResult scanResult, @NonNull String password) {
    if (connectivityManager == null) {
        return false;
    }

    WifiNetworkSpecifier.Builder wifiNetworkSpecifierBuilder = new WifiNetworkSpecifier.Builder()
            .setSsid(scanResult.SSID)
            .setBssid(MacAddress.fromString(scanResult.BSSID));

    final String security = ConfigSecurities.getSecurity(scanResult);

    ConfigSecurities.setupWifiNetworkSpecifierSecurities(wifiNetworkSpecifierBuilder, security, password);


    NetworkRequest networkRequest = new NetworkRequest.Builder()
            .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
            .setNetworkSpecifier(wifiNetworkSpecifierBuilder.build())
            .build();

    // not sure, if this is needed
    if (networkCallback != null) {
        connectivityManager.unregisterNetworkCallback(networkCallback);
    }

    networkCallback = new ConnectivityManager.NetworkCallback() {
        @Override
        public void onAvailable(@NonNull Network network) {
            super.onAvailable(network);

            wifiLog("AndroidQ+ connected to wifi ");

            // bind so all api calls are performed over this new network
            connectivityManager.bindProcessToNetwork(network);
        }

        @Override
        public void onUnavailable() {
            super.onUnavailable();

            wifiLog("AndroidQ+ could not connect to wifi");
        }
    };

    connectivityManager.requestNetwork(networkRequest, networkCallback);

    return true;
}
 
Example 12
Source File: LyricsViewFragment.java    From QuickLyric with GNU General Public License v3.0 4 votes vote down vote up
public void setNetworkCallback(ConnectivityManager.NetworkCallback networkCallback) {
    this.networkCallback = networkCallback;
}
 
Example 13
Source File: OverlayContentLayout.java    From QuickLyric with GNU General Public License v3.0 4 votes vote down vote up
public void setNetworkCallback(ConnectivityManager.NetworkCallback networkCallback) {
    this.networkCallback = networkCallback;
}
 
Example 14
Source File: AndroidChannelBuilderTest.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
private void notifyDefaultNetworkCallbacksOnAvailable(Network network) {
  for (ConnectivityManager.NetworkCallback networkCallback : defaultNetworkCallbacks) {
    networkCallback.onAvailable(network);
  }
}
 
Example 15
Source File: AndroidChannelBuilderTest.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
private void notifyDefaultNetworkCallbacksOnLost(Network network) {
  for (ConnectivityManager.NetworkCallback networkCallback : defaultNetworkCallbacks) {
    networkCallback.onLost(network);
  }
}
 
Example 16
Source File: AndroidChannelBuilderTest.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
@Implementation(minSdk = N)
@Override
protected void registerDefaultNetworkCallback(
    ConnectivityManager.NetworkCallback networkCallback) {
  defaultNetworkCallbacks.add(networkCallback);
}