android.net.Network Java Examples
The following examples show how to use
android.net.Network.
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: TcpSocketModule.java From react-native-tcp-socket with MIT License | 7 votes |
private void requestNetwork(final int transportType) throws InterruptedException { final NetworkRequest.Builder requestBuilder = new NetworkRequest.Builder(); requestBuilder.addTransportType(transportType); final CountDownLatch awaitingNetwork = new CountDownLatch(1); // only needs to be counted down once to release waiting threads final ConnectivityManager cm = (ConnectivityManager) mReactContext.getSystemService(Context.CONNECTIVITY_SERVICE); cm.requestNetwork(requestBuilder.build(), new ConnectivityManager.NetworkCallback() { @Override public void onAvailable(Network network) { currentNetwork.setNetwork(network); awaitingNetwork.countDown(); // Stop waiting } @Override public void onUnavailable() { awaitingNetwork.countDown(); // Stop waiting } }); // Timeout if there the network is unreachable ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1); exec.schedule(new Runnable() { public void run() { awaitingNetwork.countDown(); // Stop waiting } }, 5, TimeUnit.SECONDS); awaitingNetwork.await(); }
Example #2
Source File: AirplaneModeAndroidTest.java From firebase-jobdispatcher-android with Apache License 2.0 | 6 votes |
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 #3
Source File: WifiFacade.java From particle-android with Apache License 2.0 | 6 votes |
@Nullable @RequiresApi(api = VERSION_CODES.LOLLIPOP) public Network getNetworkObjectForCurrentWifiConnection() { // Android doesn't have any means of directly asking // "I want the Network obj for the Wi-Fi network with SSID <foo>". // Instead, you have to infer it based on the fact that you can only // have one connected Wi-Fi connection at a time. // (Update: one *regular* Wi-Fi connection, anyway. See below.) return Funcy.findFirstMatch( Arrays.asList(connectivityManager.getAllNetworks()), network -> { NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(network); if (capabilities == null) { return false; } // Don't try using the P2P Wi-Fi interfaces on recent Samsung devices if (capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) { return false; } return capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI); } ); }
Example #4
Source File: AndroidNetworkLibrary.java From 365browser with Apache License 2.0 | 6 votes |
/** * Returns true if the system's captive portal probe was blocked for the current default data * network. The method will return false if the captive portal probe was not blocked, the login * process to the captive portal has been successfully completed, or if the captive portal * status can't be determined. Requires ACCESS_NETWORK_STATE permission. Only available on * Android Marshmallow and later versions. Returns false on earlier versions. */ @TargetApi(Build.VERSION_CODES.M) @CalledByNative private static boolean getIsCaptivePortal() { // NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL is only available on Marshmallow and // later versions. if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return false; ConnectivityManager connectivityManager = (ConnectivityManager) ContextUtils.getApplicationContext().getSystemService( Context.CONNECTIVITY_SERVICE); if (connectivityManager == null) return false; Network network = connectivityManager.getActiveNetwork(); if (network == null) return false; NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(network); return capabilities != null && capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL); }
Example #5
Source File: Requirements.java From Telegram with GNU General Public License v2.0 | 6 votes |
private static boolean isInternetConnectivityValidated(ConnectivityManager connectivityManager) { if (Util.SDK_INT < 23) { // TODO Check internet connectivity using http://clients3.google.com/generate_204 on API // levels prior to 23. return true; } Network activeNetwork = connectivityManager.getActiveNetwork(); if (activeNetwork == null) { return false; } NetworkCapabilities networkCapabilities = connectivityManager.getNetworkCapabilities(activeNetwork); boolean validated = networkCapabilities == null || !networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED); return !validated; }
Example #6
Source File: NetUtils.java From WanAndroid with MIT License | 6 votes |
public static int getNetWorkState() { if (mContext == null) { throw new UnsupportedOperationException("please use NetUtils before init it"); } // 得到连接管理器对象 ConnectivityManager connMgr = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE); //获取所有网络连接的信息 Network[] networks = connMgr.getAllNetworks(); //通过循环将网络信息逐个取出来 for (int i = 0; i < networks.length; i++) { //获取ConnectivityManager对象对应的NetworkInfo对象 NetworkInfo networkInfo = connMgr.getNetworkInfo(networks[i]); if (networkInfo.isConnected()) { if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) { return NETWORK_MOBILE; } else { return NETWORK_WIFI; } } } return NETWORK_NONE; }
Example #7
Source File: ConnectivityController.java From android_9.0.0_r45 with Apache License 2.0 | 6 votes |
private boolean updateConstraintsSatisfied(JobStatus jobStatus, Network network, NetworkCapabilities capabilities) { // TODO: consider matching against non-active networks final boolean ignoreBlocked = (jobStatus.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) != 0; final NetworkInfo info = mConnManager.getNetworkInfoForUid(network, jobStatus.getSourceUid(), ignoreBlocked); final boolean connected = (info != null) && info.isConnected(); final boolean satisfied = isSatisfied(jobStatus, network, capabilities, mConstants); final boolean changed = jobStatus .setConnectivityConstraintSatisfied(connected && satisfied); // Pass along the evaluated network for job to use; prevents race // conditions as default routes change over time, and opens the door to // using non-default routes. jobStatus.network = network; if (DEBUG) { Slog.i(TAG, "Connectivity " + (changed ? "CHANGED" : "unchanged") + " for " + jobStatus + ": connected=" + connected + " satisfied=" + satisfied); } return changed; }
Example #8
Source File: StateMachineConnection.java From timelapse-sony with GNU General Public License v3.0 | 6 votes |
@Override public void process(final StateMachineConnection sm) { // Workaround when there is a data connection more than the wifi one // http://stackoverflow.com/questions/33237074/request-over-wifi-on-android-m if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) { ConnectivityManager connectivityManager = (ConnectivityManager) sm.mApplication.getSystemService(Context.CONNECTIVITY_SERVICE); for (Network net : connectivityManager.getAllNetworks()) { NetworkInfo netInfo = connectivityManager.getNetworkInfo(net); if (netInfo != null && netInfo.getType() == ConnectivityManager.TYPE_WIFI && netInfo.getExtraInfo() != null && netInfo.getExtraInfo() .equals(sm.mStateRegistry.wifiInfo.getSSID())) { connectivityManager.bindProcessToNetwork(net); break; } } } sm.mStateRegistry.apiAttempts = 1; sm.setCurrentState(State.CHECK_API); }
Example #9
Source File: Util.java From NetGuard with GNU General Public License v3.0 | 6 votes |
public static boolean isConnected(Context context) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); if (cm == null) return false; NetworkInfo ni = cm.getActiveNetworkInfo(); if (ni != null && ni.isConnected()) return true; Network[] networks = cm.getAllNetworks(); if (networks == null) return false; for (Network network : networks) { ni = cm.getNetworkInfo(network); if (ni != null && ni.getType() != ConnectivityManager.TYPE_VPN && ni.isConnected()) return true; } return false; }
Example #10
Source File: NetworkChangeNotifierAutoDetect.java From cronet with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * Returns connection type for |network|. * Only callable on Lollipop and newer releases. */ @TargetApi(Build.VERSION_CODES.LOLLIPOP) @ConnectionType int getConnectionType(Network network) { NetworkInfo networkInfo = getNetworkInfo(network); if (networkInfo != null && networkInfo.getType() == TYPE_VPN) { // When a VPN is in place the underlying network type can be queried via // getActiveNeworkInfo() thanks to // https://android.googlesource.com/platform/frameworks/base/+/d6a7980d networkInfo = mConnectivityManager.getActiveNetworkInfo(); } if (networkInfo != null && networkInfo.isConnected()) { return convertToConnectionType(networkInfo.getType(), networkInfo.getSubtype()); } return ConnectionType.CONNECTION_NONE; }
Example #11
Source File: MainActivity.java From Intra with Apache License 2.0 | 6 votes |
private LinkProperties getLinkProperties() { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { // getActiveNetwork() requires M or later. return null; } Network activeNetwork = connectivityManager.getActiveNetwork(); if (activeNetwork == null) { return null; } return connectivityManager.getLinkProperties(activeNetwork); }
Example #12
Source File: IPv6TetheringCoordinator.java From android_9.0.0_r45 with Apache License 2.0 | 6 votes |
private void setUpstreamNetworkState(NetworkState ns) { if (ns == null) { mUpstreamNetworkState = null; } else { // Make a deep copy of the parts we need. mUpstreamNetworkState = new NetworkState( null, new LinkProperties(ns.linkProperties), new NetworkCapabilities(ns.networkCapabilities), new Network(ns.network), null, null); } mLog.log("setUpstreamNetworkState: " + toDebugString(mUpstreamNetworkState)); }
Example #13
Source File: UpstreamNetworkMonitor.java From android_9.0.0_r45 with Apache License 2.0 | 6 votes |
private void handleLinkProp(Network network, LinkProperties newLp) { final NetworkState prev = mNetworkMap.get(network); if (prev == null || newLp.equals(prev.linkProperties)) { // Ignore notifications about networks for which we have not yet // received onAvailable() (should never happen) and any duplicate // notifications (e.g. matching more than one of our callbacks). return; } if (VDBG) { Log.d(TAG, String.format("EVENT_ON_LINKPROPERTIES for %s: %s", network, newLp)); } mNetworkMap.put(network, new NetworkState( null, newLp, prev.networkCapabilities, network, null, null)); // TODO: If sufficient information is available to select a more // preferable upstream, do so now and notify the target. notifyTarget(EVENT_ON_LINKPROPERTIES, network); }
Example #14
Source File: ConnectionHelper.java From FairEmail with GNU General Public License v3.0 | 6 votes |
static boolean vpnActive(Context context) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); if (cm == null) return false; try { for (Network network : cm.getAllNetworks()) { NetworkCapabilities caps = cm.getNetworkCapabilities(network); if (caps != null && caps.hasTransport(NetworkCapabilities.TRANSPORT_VPN)) return true; } } catch (Throwable ex) { Log.w(ex); } return false; }
Example #15
Source File: ServiceSynchronize.java From FairEmail with GNU General Public License v3.0 | 6 votes |
private void updateState(Network network, NetworkCapabilities capabilities) { ConnectionHelper.NetworkState ns = ConnectionHelper.getNetworkState(ServiceSynchronize.this); liveNetworkState.postValue(ns); if (lastSuitable == null || lastSuitable != ns.isSuitable()) { lastSuitable = ns.isSuitable(); EntityLog.log(ServiceSynchronize.this, "Updated network=" + network + " capabilities " + capabilities + " suitable=" + lastSuitable); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ServiceSynchronize.this); boolean background_service = prefs.getBoolean("background_service", false); if (!background_service) try { NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); nm.notify(Helper.NOTIFICATION_SYNCHRONIZE, getNotificationService(lastAccounts, lastOperations).build()); } catch (Throwable ex) { Log.w(ex); } } }
Example #16
Source File: NetworkConnectionReceiver.java From your-local-weather with GNU General Public License v3.0 | 5 votes |
@Override public void onAvailable(Network network) { super.onAvailable(network); appendLog(context, TAG, "onAvailable, network=", network, ", wasOffline=", wasOffline); if (networkIsOffline()) { appendLog(context, TAG, "network is offline"); wasOffline = true; return; } appendLog(context, TAG, "network is online, wasOffline=", wasOffline); if (wasOffline) { checkAndUpdateWeather(); } wasOffline = false; }
Example #17
Source File: NetworkChangeNotifierAutoDetect.java From 365browser with Apache License 2.0 | 5 votes |
void initializeVpnInPlace() { final Network[] networks = getAllNetworksFiltered(mConnectivityManagerDelegate, null); mVpnInPlace = null; // If the filtered list of networks contains just a VPN, then that VPN is in place. if (networks.length == 1) { final NetworkCapabilities capabilities = mConnectivityManagerDelegate.getNetworkCapabilities(networks[0]); if (capabilities != null && capabilities.hasTransport(TRANSPORT_VPN)) { mVpnInPlace = networks[0]; } } }
Example #18
Source File: LollipopDeviceStateListener.java From android with GNU General Public License v3.0 | 5 votes |
@Override public void onAvailable(Network network) { super.onAvailable(network); if (!network.toString().equals(mLastConnectedStatus)) { mLastConnectedStatus = network.toString(); VpnStatus.logDebug("Connected to " + mLastConnectedStatus); } }
Example #19
Source File: ServiceSynchronize.java From FairEmail with GNU General Public License v3.0 | 5 votes |
@Override public void onAvailable(@NonNull Network network) { try { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo ni = cm.getNetworkInfo(network); EntityLog.log(ServiceSynchronize.this, "Available network=" + network + " info=" + ni); } catch (Throwable ex) { Log.w(ex); } updateState(network, null); }
Example #20
Source File: GetDeviceInfo.java From appium-uiautomator2-server with Apache License 2.0 | 5 votes |
private static List<NetworkInfoModel> extractNetworkInfo(DeviceInfoHelper deviceInfoHelper) { List<NetworkInfoModel> result = new ArrayList<>(); for (Network network : deviceInfoHelper.getNetworks()) { NetworkInfoModel resultItem = new NetworkInfoModel(); NetworkInfo networkInfo = deviceInfoHelper.extractInfo(network); if (networkInfo != null) { resultItem.type = networkInfo.getType(); resultItem.typeName = networkInfo.getTypeName(); resultItem.subtype = networkInfo.getSubtype(); resultItem.subtypeName = networkInfo.getSubtypeName(); resultItem.isConnected = networkInfo.isConnected(); resultItem.detailedState = networkInfo.getDetailedState().name(); resultItem.state = networkInfo.getState().name(); resultItem.extraInfo = networkInfo.getExtraInfo(); resultItem.isAvailable = networkInfo.isAvailable(); resultItem.isFailover = networkInfo.isFailover(); resultItem.isRoaming = networkInfo.isRoaming(); } NetworkCapabilities networkCaps = deviceInfoHelper.extractCapabilities(network); NetworkCapabilitiesModel caps = new NetworkCapabilitiesModel(); if (networkCaps != null) { caps.transportTypes = DeviceInfoHelper.extractTransportTypes(networkCaps); caps.networkCapabilities = DeviceInfoHelper.extractCapNames(networkCaps); caps.linkUpstreamBandwidthKbps = networkCaps.getLinkUpstreamBandwidthKbps(); caps.linkDownBandwidthKbps = networkCaps.getLinkDownstreamBandwidthKbps(); caps.signalStrength = extractSafeValue("mSignalStrength", networkCaps); caps.SSID = extractSafeValue("mSSID", networkCaps); } resultItem.capabilities = networkCaps == null ? null : caps; if (networkInfo != null || networkCaps != null) { result.add(resultItem); } } return result; }
Example #21
Source File: LollipopDeviceStateListener.java From Cake-VPN with GNU General Public License v2.0 | 5 votes |
@Override public void onAvailable(Network network) { super.onAvailable(network); if (!network.toString().equals(mLastConnectedStatus)) { mLastConnectedStatus = network.toString(); VpnStatus.logDebug("Connected to " + mLastConnectedStatus); } }
Example #22
Source File: NetworkMonitorAutoDetect.java From webrtc_android with MIT License | 5 votes |
@Override public void onCapabilitiesChanged(Network network, NetworkCapabilities networkCapabilities) { // A capabilities change may indicate the ConnectionType has changed, // so forward the new NetworkInformation along to the observer. Logging.d(TAG, "capabilities changed: " + networkCapabilities.toString()); onNetworkChanged(network); }
Example #23
Source File: NetworkMonitorAutoDetect.java From webrtc_android with MIT License | 5 votes |
@Override public void onLinkPropertiesChanged(Network network, LinkProperties linkProperties) { // A link property change may indicate the IP address changes. // so forward the new NetworkInformation to the observer. Logging.d(TAG, "link properties changed: " + linkProperties.toString()); onNetworkChanged(network); }
Example #24
Source File: JNIUtilities.java From TelePlus-Android with GNU General Public License v2.0 | 5 votes |
@TargetApi(23) public static String getCurrentNetworkInterfaceName(){ ConnectivityManager cm=(ConnectivityManager) ApplicationLoader.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE); Network net=cm.getActiveNetwork(); if(net==null) return null; LinkProperties props=cm.getLinkProperties(net); if(props==null) return null; return props.getInterfaceName(); }
Example #25
Source File: NetworkMonitorAutoDetect.java From webrtc_android with MIT License | 5 votes |
/** * Returns all connected networks. * Only callable on Lollipop and newer releases. */ @SuppressLint("NewApi") Network[] getAllNetworks() { if (connectivityManager == null) { return new Network[0]; } return connectivityManager.getAllNetworks(); }
Example #26
Source File: NetworkMonitorAutoDetect.java From webrtc_android with MIT License | 5 votes |
/** * Returns the NetID of the current default network. Returns * INVALID_NET_ID if no current default network connected. * Only callable on Lollipop and newer releases. */ @SuppressLint("NewApi") long getDefaultNetId() { if (!supportNetworkCallback()) { return INVALID_NET_ID; } // Android Lollipop had no API to get the default network; only an // API to return the NetworkInfo for the default network. To // determine the default network one can find the network with // type matching that of the default network. final NetworkInfo defaultNetworkInfo = connectivityManager.getActiveNetworkInfo(); if (defaultNetworkInfo == null) { return INVALID_NET_ID; } final Network[] networks = getAllNetworks(); long defaultNetId = INVALID_NET_ID; for (Network network : networks) { if (!hasInternetCapability(network)) { continue; } final NetworkInfo networkInfo = connectivityManager.getNetworkInfo(network); if (networkInfo != null && networkInfo.getType() == defaultNetworkInfo.getType()) { // There should not be multiple connected networks of the // same type. At least as of Android Marshmallow this is // not supported. If this becomes supported this assertion // may trigger. At that point we could consider using // ConnectivityManager.getDefaultNetwork() though this // may give confusing results with VPNs and is only // available with Android Marshmallow. if (defaultNetId != INVALID_NET_ID) { throw new RuntimeException( "Multiple connected networks of same type are not supported."); } defaultNetId = networkToNetId(network); } } return defaultNetId; }
Example #27
Source File: NetworkChangeNotifierAutoDetect.java From cronet with BSD 3-Clause "New" or "Revised" License | 5 votes |
/** * Extracts NetID of Network on Lollipop and NetworkHandle (which is munged NetID) on * Marshmallow and newer releases. Only available on Lollipop and newer releases. */ @TargetApi(Build.VERSION_CODES.LOLLIPOP) @VisibleForTesting static long networkToNetId(Network network) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { return ApiHelperForM.getNetworkHandle(network); } else { // NOTE(pauljensen): This depends on Android framework implementation details. These // details cannot change because Lollipop is long since released. // NetIDs are only 16-bit so use parseInt. This function returns a long because // getNetworkHandle() returns a long. return Integer.parseInt(network.toString()); } }
Example #28
Source File: LollipopDeviceStateListener.java From SimpleOpenVpn-Android with Apache License 2.0 | 5 votes |
@Override public void onAvailable(Network network) { super.onAvailable(network); if (!network.toString().equals(mLastConnectedStatus)) { mLastConnectedStatus = network.toString(); VpnStatus.logDebug("Connected to " + mLastConnectedStatus); } }
Example #29
Source File: ServiceSynchronize.java From FairEmail with GNU General Public License v3.0 | 5 votes |
@Override public void onLost(@NonNull Network network) { try { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo ani = cm.getActiveNetworkInfo(); EntityLog.log(ServiceSynchronize.this, "Lost network=" + network + " active=" + ani); if (ani == null) lastLost = new Date().getTime(); } catch (Throwable ex) { Log.w(ex); } updateState(network, null); }
Example #30
Source File: MainActivity.java From wear-os-samples with Apache License 2.0 | 5 votes |
private boolean isNetworkHighBandwidth() { Network network = mConnectivityManager.getBoundNetworkForProcess(); network = network == null ? mConnectivityManager.getActiveNetwork() : network; if (network == null) { return false; } // requires android.permission.ACCESS_NETWORK_STATE int bandwidth = mConnectivityManager .getNetworkCapabilities(network).getLinkDownstreamBandwidthKbps(); return bandwidth >= MIN_NETWORK_BANDWIDTH_KBPS; }