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 vote down vote up
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 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 #3
Source File: NetworkChangeNotifierAutoDetect.java    From cronet with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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 #4
Source File: MainActivity.java    From Intra with Apache License 2.0 6 votes vote down vote up
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 #5
Source File: Util.java    From NetGuard with GNU General Public License v3.0 6 votes vote down vote up
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 #6
Source File: Requirements.java    From Telegram with GNU General Public License v2.0 6 votes vote down vote up
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 #7
Source File: IPv6TetheringCoordinator.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
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 #8
Source File: UpstreamNetworkMonitor.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
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 #9
Source File: ConnectionHelper.java    From FairEmail with GNU General Public License v3.0 6 votes vote down vote up
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 #10
Source File: AndroidNetworkLibrary.java    From 365browser with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #11
Source File: StateMachineConnection.java    From timelapse-sony with GNU General Public License v3.0 6 votes vote down vote up
@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 #12
Source File: NetUtils.java    From WanAndroid with MIT License 6 votes vote down vote up
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 #13
Source File: ConnectivityController.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
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 #14
Source File: ServiceSynchronize.java    From FairEmail with GNU General Public License v3.0 6 votes vote down vote up
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 #15
Source File: WifiFacade.java    From particle-android with Apache License 2.0 6 votes vote down vote up
@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 #16
Source File: AptoideUtils.java    From aptoide-client with GNU General Public License v2.0 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private static boolean isAvailableSdk21(final ConnectivityManager manager,
                                        final int networkType) {
    for (final Network network : manager.getAllNetworks()) {
        final NetworkInfo info = manager.getNetworkInfo(network);
        if (info != null && info.isConnected() && info.getType() == networkType) {
            return true;
        }
    }
    return false;
}
 
Example #17
Source File: NetworkChangeNotifierAutoDetect.java    From cronet with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Returns an array of all of the device's currently connected
 * networks and ConnectionTypes, including only those that are useful and accessible to Chrome.
 * Array elements are a repeated sequence of:
 *   NetID of network
 *   ConnectionType of network
 * Only available on Lollipop and newer releases and when auto-detection has
 * been enabled.
 */
public long[] getNetworksAndTypes() {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        return new long[0];
    }
    final Network networks[] = getAllNetworksFiltered(mConnectivityManagerDelegate, null);
    final long networksAndTypes[] = new long[networks.length * 2];
    int index = 0;
    for (Network network : networks) {
        networksAndTypes[index++] = networkToNetId(network);
        networksAndTypes[index++] = mConnectivityManagerDelegate.getConnectionType(network);
    }
    return networksAndTypes;
}
 
Example #18
Source File: UpstreamNetworkMonitor.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
@Override
public void onLinkPropertiesChanged(Network network, LinkProperties newLp) {
    handleLinkProp(network, newLp);
    // TODO(b/110335330): reduce the number of times this is called by
    // only recomputing on the LISTEN_ALL callback.
    recomputeLocalPrefixes();
}
 
Example #19
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 #20
Source File: LocalIPUtil.java    From DanDanPlayForAndroid with MIT License 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private LinkProperties getLinkProperties(ConnectivityManager connectivityManager, int cap) {
    Network nets[] = connectivityManager.getAllNetworks();
    for (Network n: nets) {
        LinkProperties linkProperties = connectivityManager.getLinkProperties(n);
        NetworkCapabilities networkCapabilities = connectivityManager.getNetworkCapabilities(n);
        String interfaceName =  linkProperties.getInterfaceName();
        if (interfaceName != null && networkCapabilities != null) {
            if (networkCapabilities.hasTransport(cap))
                return linkProperties;
        }
    }
    return null;
}
 
Example #21
Source File: NetWorkUtils.java    From DevUtils with Apache License 2.0 5 votes vote down vote up
/**
 * 获取连接的网络类型
 * @return -1 = 等于未知, 1 = Wifi, 2 = 移动网络
 */
@RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
public static int getConnectType() {
    try {
        // 获取手机所有连接管理对象 ( 包括对 wi-fi,net 等连接的管理 )
        ConnectivityManager cManager = AppUtils.getConnectivityManager();
        // 版本兼容处理
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) {
            // 判断连接的是否 Wifi
            State wifiState = cManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
            // 判断是否连接上
            if (wifiState == State.CONNECTED || wifiState == State.CONNECTING) {
                return 1;
            } else {
                // 判断连接的是否移动网络
                State mobileState = cManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
                // 判断移动网络是否连接上
                if (mobileState == State.CONNECTED || mobileState == State.CONNECTING) {
                    return 2;
                }
            }
        } else {
            // 获取当前活跃的网络 ( 连接的网络信息 )
            Network network = cManager.getActiveNetwork();
            if (network != null) {
                NetworkCapabilities networkCapabilities = cManager.getNetworkCapabilities(network);
                // 判断连接的是否 Wifi
                if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
                    return 1;
                } else if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
                    // 判断连接的是否移动网络
                    return 2;
                }
            }
        }
    } catch (Exception e) {
        LogPrintUtils.eTag(TAG, e, "getConnectType");
    }
    return -1;
}
 
Example #22
Source File: NetdEventListenerService.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private long getTransports(int netId) {
    // TODO: directly query ConnectivityService instead of going through Binder interface.
    NetworkCapabilities nc = mCm.getNetworkCapabilities(new Network(netId));
    if (nc == null) {
        return 0;
    }
    return BitUtils.packBits(nc.getTransportTypes());
}
 
Example #23
Source File: NetWorkReceiver.java    From DevUtils with Apache License 2.0 5 votes vote down vote up
/**
 * 获取连接的网络类型
 * @return 连接的网络类型
 */
@RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
public static int getConnectType() {
    // 获取手机所有连接管理对象 ( 包括对 wi-fi,net 等连接的管理 )
    try {
        // 获取网络连接状态
        ConnectivityManager cManager = AppUtils.getConnectivityManager();
        // 版本兼容处理
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) {
            // 判断连接的是否 Wifi
            NetworkInfo.State wifiState = cManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
            // 判断是否连接上
            if (wifiState == NetworkInfo.State.CONNECTED || wifiState == NetworkInfo.State.CONNECTING) {
                return NET_WIFI;
            } else {
                // 判断连接的是否移动网络
                NetworkInfo.State mobileState = cManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
                // 判断移动网络是否连接上
                if (mobileState == NetworkInfo.State.CONNECTED || mobileState == NetworkInfo.State.CONNECTING) {
                    return NET_MOBILE;
                }
            }
        } else {
            // 获取当前活跃的网络 ( 连接的网络信息 )
            Network network = cManager.getActiveNetwork();
            if (network != null) {
                NetworkCapabilities networkCapabilities = cManager.getNetworkCapabilities(network);
                // 判断连接的是否 Wifi
                if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
                    return NET_WIFI;
                } else if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
                    return NET_MOBILE;
                }
            }
        }
    } catch (Exception e) {
        LogPrintUtils.eTag(TAG, e, "getConnectType");
    }
    return NO_NETWORK;
}
 
Example #24
Source File: AndroidUsingLinkProperties.java    From Conversations with GNU General Public License v3.0 5 votes vote down vote up
@Override
@TargetApi(21)
public String[] getDnsServerAddresses() {
    final ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    final Network[] networks = connectivityManager == null ? null : connectivityManager.getAllNetworks();
    if (networks == null) {
        return new String[0];
    }
    final Network activeNetwork = getActiveNetwork(connectivityManager);
    final List<String> servers = new ArrayList<>();
    int vpnOffset = 0;
    for(Network network : networks) {
        LinkProperties linkProperties = connectivityManager.getLinkProperties(network);
        if (linkProperties == null) {
            continue;
        }
        final NetworkInfo networkInfo = connectivityManager.getNetworkInfo(network);
        final boolean isActiveNetwork = network.equals(activeNetwork);
        final boolean isVpn = networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_VPN;
        if (isActiveNetwork && isVpn) {
            final List<String> tmp = getIPv4First(linkProperties.getDnsServers());
            servers.addAll(0, tmp);
            vpnOffset += tmp.size();
        } else if (hasDefaultRoute(linkProperties) || isActiveNetwork || activeNetwork == null || isVpn) {
            servers.addAll(vpnOffset, getIPv4First(linkProperties.getDnsServers()));
        }
    }
    return servers.toArray(new String[0]);
}
 
Example #25
Source File: NetworkConnectionReceiver.java    From your-local-weather with GNU General Public License v3.0 5 votes vote down vote up
@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 #26
Source File: NetworkMonitor.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
@Override
public boolean processMessage(Message message) {
    switch (message.what) {
        case CMD_LAUNCH_CAPTIVE_PORTAL_APP:
            final Intent intent = new Intent(
                    ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
            // OneAddressPerFamilyNetwork is not parcelable across processes.
            intent.putExtra(ConnectivityManager.EXTRA_NETWORK, new Network(mNetwork));
            intent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
                    new CaptivePortal(new ICaptivePortal.Stub() {
                        @Override
                        public void appResponse(int response) {
                            if (response == APP_RETURN_WANTED_AS_IS) {
                                mContext.enforceCallingPermission(
                                        android.Manifest.permission.CONNECTIVITY_INTERNAL,
                                        "CaptivePortal");
                            }
                            sendMessage(CMD_CAPTIVE_PORTAL_APP_FINISHED, response);
                        }
                    }));
            final CaptivePortalProbeResult probeRes = mLastPortalProbeResult;
            intent.putExtra(EXTRA_CAPTIVE_PORTAL_URL, probeRes.detectUrl);
            if (probeRes.probeSpec != null) {
                final String encodedSpec = probeRes.probeSpec.getEncodedSpec();
                intent.putExtra(EXTRA_CAPTIVE_PORTAL_PROBE_SPEC, encodedSpec);
            }
            intent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL_USER_AGENT,
                    mCaptivePortalUserAgent);
            intent.setFlags(
                    Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
            mContext.startActivityAsUser(intent, UserHandle.CURRENT);
            return HANDLED;
        default:
            return NOT_HANDLED;
    }
}
 
Example #27
Source File: WifiUtils.java    From mosmetro-android with GNU General Public License v3.0 5 votes vote down vote up
@Nullable
@RequiresApi(21)
public Network getNetwork() {
    Network result = getNetwork(ConnectivityManager.TYPE_VPN);
    if (result == null) {
        result = getNetwork(ConnectivityManager.TYPE_WIFI);
    }
    return result;
}
 
Example #28
Source File: ConnectivityHelper.java    From libcommon with Apache License 2.0 5 votes vote down vote up
@SuppressLint("MissingPermission")
@Override
public void onLost(@NonNull final Network network) {
	super.onLost(network);
	// 接続を失った時
	if (DEBUG) Log.v(TAG, String.format("onLost:Network(%s)", network));
	updateActiveNetwork(network);
}
 
Example #29
Source File: DeviceInfoHelper.java    From appium-uiautomator2-server with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves the information about the given network
 *
 * @param net android network object
 * @return Network info
 */
@Nullable
public NetworkInfo extractInfo(Network net) {
    return connManager == null
            ? null
            : connManager.getNetworkInfo(net);
}
 
Example #30
Source File: NetworkChangeNotifierAutoDetect.java    From 365browser with Apache License 2.0 5 votes vote down vote up
/**
 * Registers a BroadcastReceiver in the given context.
 */
public void register() {
    assertOnThread();
    if (mRegistered) return;

    if (mShouldSignalObserver) {
        connectionTypeChanged();
    }
    // When registering for a sticky broadcast, like CONNECTIVITY_ACTION, if registerReceiver
    // returns non-null, it means the broadcast was previously issued and onReceive() will be
    // immediately called with this previous Intent. Since this initial callback doesn't
    // actually indicate a network change, we can ignore it by setting mIgnoreNextBroadcast.
    mIgnoreNextBroadcast =
            ContextUtils.getApplicationContext().registerReceiver(this, mIntentFilter) != null;
    mRegistered = true;

    if (mNetworkCallback != null) {
        mNetworkCallback.initializeVpnInPlace();
        mConnectivityManagerDelegate.registerNetworkCallback(mNetworkRequest, mNetworkCallback);
        if (mShouldSignalObserver) {
            // registerNetworkCallback() will rematch the NetworkRequest
            // against active networks, so a cached list of active networks
            // will be repopulated immediatly after this. However we need to
            // purge any cached networks as they may have been disconnected
            // while mNetworkCallback was unregistered.
            final Network[] networks =
                    getAllNetworksFiltered(mConnectivityManagerDelegate, null);
            // Convert Networks to NetIDs.
            final long[] netIds = new long[networks.length];
            for (int i = 0; i < networks.length; i++) {
                netIds[i] = networkToNetId(networks[i]);
            }
            mObserver.purgeActiveNetworkList(netIds);
        }
    }
}