android.net.NetworkInfo.DetailedState Java Examples

The following examples show how to use android.net.NetworkInfo.DetailedState. 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: Vpn.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Update current state, dispaching event to listeners.
 */
@VisibleForTesting
protected void updateState(DetailedState detailedState, String reason) {
    if (LOGD) Log.d(TAG, "setting state=" + detailedState + ", reason=" + reason);
    mNetworkInfo.setDetailedState(detailedState, reason, null);
    if (mNetworkAgent != null) {
        mNetworkAgent.sendNetworkInfo(mNetworkInfo);
    }
    updateAlwaysOnNotification(detailedState);
}
 
Example #2
Source File: Vpn.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private void agentConnect() {
    LinkProperties lp = makeLinkProperties();

    if (providesRoutesToMostDestinations(lp)) {
        mNetworkCapabilities.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
    } else {
        mNetworkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
    }

    mNetworkInfo.setDetailedState(DetailedState.CONNECTING, null, null);

    NetworkMisc networkMisc = new NetworkMisc();
    networkMisc.allowBypass = mConfig.allowBypass && !mLockdown;

    mNetworkCapabilities.setEstablishingVpnAppUid(Binder.getCallingUid());
    mNetworkCapabilities.setUids(createUserAndRestrictedProfilesRanges(mUserHandle,
            mConfig.allowedApplications, mConfig.disallowedApplications));
    long token = Binder.clearCallingIdentity();
    try {
        mNetworkAgent = new NetworkAgent(mLooper, mContext, NETWORKTYPE /* logtag */,
                mNetworkInfo, mNetworkCapabilities, lp,
                ConnectivityConstants.VPN_DEFAULT_SCORE, networkMisc) {
                        @Override
                        public void unwanted() {
                            // We are user controlled, not driven by NetworkRequest.
                        }
                    };
    } finally {
        Binder.restoreCallingIdentity(token);
    }
    mNetworkInfo.setIsAvailable(true);
    updateState(DetailedState.CONNECTED, "agentConnect");
}
 
Example #3
Source File: Vpn.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private void agentDisconnect(NetworkAgent networkAgent) {
    if (networkAgent != null) {
        NetworkInfo networkInfo = new NetworkInfo(mNetworkInfo);
        networkInfo.setIsAvailable(false);
        networkInfo.setDetailedState(DetailedState.DISCONNECTED, null, null);
        networkAgent.sendNetworkInfo(networkInfo);
    }
}
 
Example #4
Source File: Vpn.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private void agentDisconnect() {
    if (mNetworkInfo.isConnected()) {
        mNetworkInfo.setIsAvailable(false);
        updateState(DetailedState.DISCONNECTED, "agentDisconnect");
        mNetworkAgent = null;
    }
}
 
Example #5
Source File: Vpn.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private void updateAlwaysOnNotification(DetailedState networkState) {
    final boolean visible = (mAlwaysOn && networkState != DetailedState.CONNECTED);

    final UserHandle user = UserHandle.of(mUserHandle);
    final long token = Binder.clearCallingIdentity();
    try {
        final NotificationManager notificationManager = NotificationManager.from(mContext);
        if (!visible) {
            notificationManager.cancelAsUser(TAG, SystemMessage.NOTE_VPN_DISCONNECTED, user);
            return;
        }
        final Intent intent = new Intent();
        intent.setComponent(ComponentName.unflattenFromString(mContext.getString(
                R.string.config_customVpnAlwaysOnDisconnectedDialogComponent)));
        intent.putExtra("lockdown", mLockdown);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        final PendingIntent configIntent = mSystemServices.pendingIntentGetActivityAsUser(
                intent, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT, user);
        final Notification.Builder builder =
                new Notification.Builder(mContext, SystemNotificationChannels.VPN)
                        .setSmallIcon(R.drawable.vpn_connected)
                        .setContentTitle(mContext.getString(R.string.vpn_lockdown_disconnected))
                        .setContentText(mContext.getString(R.string.vpn_lockdown_config))
                        .setContentIntent(configIntent)
                        .setCategory(Notification.CATEGORY_SYSTEM)
                        .setVisibility(Notification.VISIBILITY_PUBLIC)
                        .setOngoing(true)
                        .setColor(mContext.getColor(R.color.system_notification_accent_color));
        notificationManager.notifyAsUser(TAG, SystemMessage.NOTE_VPN_DISCONNECTED,
                builder.build(), user);
    } finally {
        Binder.restoreCallingIdentity(token);
    }
}
 
Example #6
Source File: Vpn.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private synchronized void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
    stopLegacyVpnPrivileged();

    // Prepare for the new request.
    prepareInternal(VpnConfig.LEGACY_VPN);
    updateState(DetailedState.CONNECTING, "startLegacyVpn");

    // Start a new LegacyVpnRunner and we are done!
    mLegacyVpnRunner = new LegacyVpnRunner(config, racoon, mtpd);
    mLegacyVpnRunner.start();
}
 
Example #7
Source File: Vpn.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private void checkInterruptAndDelay(boolean sleepLonger) throws InterruptedException {
    long now = SystemClock.elapsedRealtime();
    if (now - mBringupStartTime <= 60000) {
        Thread.sleep(sleepLonger ? 200 : 1);
    } else {
        updateState(DetailedState.FAILED, "checkpoint");
        throw new IllegalStateException("VPN bringup took too long");
    }
}
 
Example #8
Source File: LockdownVpnTracker.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
public void onVpnStateChanged(NetworkInfo info) {
    if (info.getDetailedState() == DetailedState.FAILED) {
        mErrorCount++;
    }
    synchronized (mStateLock) {
        handleStateChangedLocked();
    }
}
 
Example #9
Source File: PersistentHookDefinitions.java    From FuzzDroid with Apache License 2.0 5 votes vote down vote up
private Set<HookInfo> networkRelatedHooks() {
	Set<HookInfo> networkHooks = new HashSet<HookInfo>();
	MethodHookInfo getActiveNetworkInfo = new MethodHookInfo("<android.net.ConnectivityManager: android.net.NetworkInfo getActiveNetworkInfo()>");
	try {
		Class<?> networkInfo = Class.forName("android.net.NetworkInfo");
		Class<?>[] networkInfoParams = new Class[4];
		networkInfoParams[0] = int.class;
		networkInfoParams[1] = int.class;
		networkInfoParams[2] = String.class;
		networkInfoParams[3] = String.class;
		Constructor<?> init = networkInfo.getConstructor(networkInfoParams);
		init.setAccessible(true);
		Object obj = init.newInstance(0, 3, "mobile", "UMTS");
		Class<?>[] booleanParam = new Class[1];
		booleanParam[0] = boolean.class;
		Method setIsAvailable = networkInfo.getMethod("setIsAvailable", booleanParam);
		setIsAvailable.setAccessible(true);
		setIsAvailable.invoke(obj, true);
		Method setIsConnectedToProvisioningNetwork = networkInfo.getMethod("setIsConnectedToProvisioningNetwork", booleanParam);
		setIsConnectedToProvisioningNetwork.setAccessible(true);
		setIsConnectedToProvisioningNetwork.invoke(obj, true);
		Method setRoaming = networkInfo.getMethod("setRoaming", booleanParam);
		setRoaming.setAccessible(true);
		setRoaming.invoke(obj, true);
		Class<?>[] setDetailedStateParams = new Class[3];
		setDetailedStateParams[0] = DetailedState.class;
		setDetailedStateParams[1] = String.class;
		setDetailedStateParams[2] = String.class;
		Method setDetailedState = networkInfo.getMethod("setDetailedState", setDetailedStateParams);
		setDetailedState.setAccessible(true);
		setDetailedState.invoke(obj, DetailedState.CONNECTED, "connected", "epc.tmobile.com");
		getActiveNetworkInfo.persistentHookAfter(obj);
	}catch(Exception ex) {
		ex.printStackTrace();
	}
			
	networkHooks.add(getActiveNetworkInfo);
	return networkHooks;
}
 
Example #10
Source File: LockdownVpnTracker.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
/**
 * Watch for state changes to both active egress network, kicking off a VPN
 * connection when ready, or setting firewall rules once VPN is connected.
 */
private void handleStateChangedLocked() {

    final NetworkInfo egressInfo = mConnService.getActiveNetworkInfoUnfiltered();
    final LinkProperties egressProp = mConnService.getActiveLinkProperties();

    final NetworkInfo vpnInfo = mVpn.getNetworkInfo();
    final VpnConfig vpnConfig = mVpn.getLegacyVpnConfig();

    // Restart VPN when egress network disconnected or changed
    final boolean egressDisconnected = egressInfo == null
            || State.DISCONNECTED.equals(egressInfo.getState());
    final boolean egressChanged = egressProp == null
            || !TextUtils.equals(mAcceptedEgressIface, egressProp.getInterfaceName());

    final String egressTypeName = (egressInfo == null) ?
            null : ConnectivityManager.getNetworkTypeName(egressInfo.getType());
    final String egressIface = (egressProp == null) ?
            null : egressProp.getInterfaceName();
    Slog.d(TAG, "handleStateChanged: egress=" + egressTypeName +
            " " + mAcceptedEgressIface + "->" + egressIface);

    if (egressDisconnected || egressChanged) {
        mAcceptedEgressIface = null;
        mVpn.stopLegacyVpnPrivileged();
    }
    if (egressDisconnected) {
        hideNotification();
        return;
    }

    final int egressType = egressInfo.getType();
    if (vpnInfo.getDetailedState() == DetailedState.FAILED) {
        EventLogTags.writeLockdownVpnError(egressType);
    }

    if (mErrorCount > MAX_ERROR_COUNT) {
        showNotification(R.string.vpn_lockdown_error, R.drawable.vpn_disconnected);

    } else if (egressInfo.isConnected() && !vpnInfo.isConnectedOrConnecting()) {
        if (mProfile.isValidLockdownProfile()) {
            Slog.d(TAG, "Active network connected; starting VPN");
            EventLogTags.writeLockdownVpnConnecting(egressType);
            showNotification(R.string.vpn_lockdown_connecting, R.drawable.vpn_disconnected);

            mAcceptedEgressIface = egressProp.getInterfaceName();
            try {
                // Use the privileged method because Lockdown VPN is initiated by the system, so
                // no additional permission checks are necessary.
                mVpn.startLegacyVpnPrivileged(mProfile, KeyStore.getInstance(), egressProp);
            } catch (IllegalStateException e) {
                mAcceptedEgressIface = null;
                Slog.e(TAG, "Failed to start VPN", e);
                showNotification(R.string.vpn_lockdown_error, R.drawable.vpn_disconnected);
            }
        } else {
            Slog.e(TAG, "Invalid VPN profile; requires IP-based server and DNS");
            showNotification(R.string.vpn_lockdown_error, R.drawable.vpn_disconnected);
        }

    } else if (vpnInfo.isConnected() && vpnConfig != null) {
        final String iface = vpnConfig.interfaze;
        final List<LinkAddress> sourceAddrs = vpnConfig.addresses;

        if (TextUtils.equals(iface, mAcceptedIface)
              && sourceAddrs.equals(mAcceptedSourceAddr)) {
            return;
        }

        Slog.d(TAG, "VPN connected using iface=" + iface +
                ", sourceAddr=" + sourceAddrs.toString());
        EventLogTags.writeLockdownVpnConnected(egressType);
        showNotification(R.string.vpn_lockdown_connected, R.drawable.vpn_connected);

        final NetworkInfo clone = new NetworkInfo(egressInfo);
        augmentNetworkInfo(clone);
        mConnService.sendConnectedBroadcast(clone);
    }
}
 
Example #11
Source File: SipService.java    From CSipSimple with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Ask to take the control of the wifi and the partial wake lock if
 * configured
 */
private synchronized void acquireResources() {
	if(holdResources) {
		return;
	}
	
	// Add a wake lock for CPU if necessary
	if (prefsWrapper.getPreferenceBooleanValue(SipConfigManager.USE_PARTIAL_WAKE_LOCK)) {
		PowerManager pman = (PowerManager) getSystemService(Context.POWER_SERVICE);
		if (wakeLock == null) {
			wakeLock = pman.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "com.csipsimple.SipService");
			wakeLock.setReferenceCounted(false);
		}
		// Extra check if set reference counted is false ???
		if (!wakeLock.isHeld()) {
			wakeLock.acquire();
		}
	}

	// Add a lock for WIFI if necessary
	WifiManager wman = (WifiManager) getSystemService(Context.WIFI_SERVICE);
	if (wifiLock == null) {
		int mode = WifiManager.WIFI_MODE_FULL;
		if(Compatibility.isCompatible(9) && prefsWrapper.getPreferenceBooleanValue(SipConfigManager.LOCK_WIFI_PERFS)) {
			mode = 0x3; // WIFI_MODE_FULL_HIGH_PERF 
		}
		wifiLock = wman.createWifiLock(mode, "com.csipsimple.SipService");
		wifiLock.setReferenceCounted(false);
	}
	if (prefsWrapper.getPreferenceBooleanValue(SipConfigManager.LOCK_WIFI) && !wifiLock.isHeld()) {
		WifiInfo winfo = wman.getConnectionInfo();
		if (winfo != null) {
			DetailedState dstate = WifiInfo.getDetailedStateOf(winfo.getSupplicantState());
			// We assume that if obtaining ip addr, we are almost connected
			// so can keep wifi lock
			if (dstate == DetailedState.OBTAINING_IPADDR || dstate == DetailedState.CONNECTED) {
				if (!wifiLock.isHeld()) {
					wifiLock.acquire();
				}
			}
		}
	}
	holdResources = true;
}
 
Example #12
Source File: NetworkHelper.java    From letv with Apache License 2.0 4 votes vote down vote up
public static DetailedState getWifiConnectivityState(Context context) {
    NetworkInfo networkInfo = getNetworkInfo(context, 1);
    return networkInfo == null ? DetailedState.FAILED : networkInfo.getDetailedState();
}
 
Example #13
Source File: InformationCollector.java    From open-rmbt with Apache License 2.0 4 votes vote down vote up
private void getWiFiInfo()
    {
        initNetwork();
        if (wifiManager != null)
        {
            final WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            fullInfo.setProperty("WIFI_SSID",
            String.valueOf(Helperfunctions.removeQuotationsInCurrentSSIDForJellyBean(wifiInfo.getSSID())));
            		
            /*
             * fullInfo.setProperty("WIFI_LINKSPEED",
             * String.valueOf(wifiInfo.getLinkSpeed()));
             */
            fullInfo.setProperty("WIFI_BSSID", String.valueOf(wifiInfo.getBSSID()));
            fullInfo.setProperty("WIFI_NETWORK_ID", String.valueOf(wifiInfo.getNetworkId()));
            /*
             * fullInfo.setProperty("WIFI_RSSI",
             * String.valueOf(wifiInfo.getRssi()));
             */
            final SupplicantState wifiState = wifiInfo.getSupplicantState();
            fullInfo.setProperty("WIFI_SUPPLICANT_STATE", String.valueOf(wifiState.name()));
            final DetailedState wifiDetail = WifiInfo.getDetailedStateOf(wifiState);
            fullInfo.setProperty("WIFI_SUPPLICANT_STATE_DETAIL", String.valueOf(wifiDetail.name()));
            
            if (getNetwork() == NETWORK_WIFI)
            {
                
                final int rssi = wifiInfo.getRssi();
                if (rssi != -1 && rssi >= ACCEPT_WIFI_RSSI_MIN)
                {
                    int linkSpeed = wifiInfo.getLinkSpeed();
                    if (linkSpeed < 0) {
                        linkSpeed = 0;
                    }
                    
                    final SignalItem signalItem = SignalItem.getWifiSignalItem(linkSpeed, rssi);
                    if (this.collectInformation) {
                        signals.add(signalItem);	
                    }
                    lastSignalItem.set(signalItem);
                    signal.set(rssi);
                    signalType.set(SINGAL_TYPE_WLAN);
//                    Log.i(DEBUG_TAG, "Signals1: " + signals.toString());
                }
            }
        }
    }