Search in sources :

Example 1 with NetworkRequest

use of android.net.NetworkRequest in project platform_frameworks_base by android.

the class CaptivePortalLoginActivity method requestNetworkForCaptivePortal.

private void requestNetworkForCaptivePortal() {
    NetworkRequest request = new NetworkRequest.Builder().addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR).addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED).build();
    mNetworkCallback = new ConnectivityManager.NetworkCallback() {

        @Override
        public void onAvailable(Network network) {
            if (DBG)
                logd("Network available: " + network);
            mCm.bindProcessToNetwork(network);
            mNetwork = network;
            runOnUiThreadIfNotFinishing(() -> {
                // Start initial page load so WebView finishes loading proxy settings.
                // Actual load of mUrl is initiated by MyWebViewClient.
                mWebView.loadData("", "text/html", null);
            });
        }

        @Override
        public void onUnavailable() {
            if (DBG)
                logd("Network unavailable");
            runOnUiThreadIfNotFinishing(() -> {
                // Instead of not loading anything in webview, simply load the page and return
                // HTTP error page in the absence of network connection.
                mWebView.loadUrl(mUrl.toString());
            });
        }
    };
    logd("request Network for captive portal");
    mCm.requestNetwork(request, mNetworkCallback, NETWORK_REQUEST_TIMEOUT_MS);
}
Also used : ConnectivityManager(android.net.ConnectivityManager) Network(android.net.Network) NetworkRequest(android.net.NetworkRequest) NetworkCallback(android.net.ConnectivityManager.NetworkCallback)

Example 2 with NetworkRequest

use of android.net.NetworkRequest in project platform_frameworks_base by android.

the class ConnectivityService method handleAsyncChannelDisconnected.

private void handleAsyncChannelDisconnected(Message msg) {
    NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
    if (nai != null) {
        if (DBG) {
            log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
        }
        // disconnect the channel.
        if (nai.networkInfo.isConnected()) {
            nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
        }
        final boolean wasDefault = isDefaultNetwork(nai);
        if (wasDefault) {
            mDefaultInetConditionPublished = 0;
            // Log default network disconnection before required book-keeping.
            // Let rematchAllNetworksAndRequests() below record a new default network event
            // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
            // whose timestamps tell how long it takes to recover a default network.
            logDefaultNetworkEvent(null, nai);
        }
        notifyIfacesChangedForNetworkStats();
        // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
        // by other networks that are already connected. Perhaps that can be done by
        // sending all CALLBACK_LOST messages (for requests, not listens) at the end
        // of rematchAllNetworksAndRequests
        notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
        mKeepaliveTracker.handleStopAllKeepalives(nai, ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
        nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
        mNetworkAgentInfos.remove(msg.replyTo);
        updateClat(null, nai.linkProperties, nai);
        synchronized (mNetworkForNetId) {
            // Remove the NetworkAgent, but don't mark the netId as
            // available until we've told netd to delete it below.
            mNetworkForNetId.remove(nai.network.netId);
        }
        // Remove all previously satisfied requests.
        for (int i = 0; i < nai.numNetworkRequests(); i++) {
            NetworkRequest request = nai.requestAt(i);
            NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
            if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
                mNetworkForRequestId.remove(request.requestId);
                sendUpdatedScoreToFactories(request, 0);
            }
        }
        nai.clearLingerState();
        if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
            removeDataActivityTracking(nai);
            notifyLockdownVpn(nai);
            requestNetworkTransitionWakelock(nai.name());
        }
        mLegacyTypeTracker.remove(nai, wasDefault);
        rematchAllNetworksAndRequests(null, 0);
        mLingerMonitor.noteDisconnect(nai);
        if (nai.created) {
            // long time.
            try {
                mNetd.removeNetwork(nai.network.netId);
            } catch (Exception e) {
                loge("Exception removing network: " + e);
            }
        }
        synchronized (mNetworkForNetId) {
            mNetIdInUse.delete(nai.network.netId);
        }
    } else {
        NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
        if (DBG && nfi != null)
            log("unregisterNetworkFactory for " + nfi.name);
    }
}
Also used : NetworkAgentInfo(com.android.server.connectivity.NetworkAgentInfo) NetworkRequest(android.net.NetworkRequest) RemoteException(android.os.RemoteException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) FileNotFoundException(java.io.FileNotFoundException) XmlPullParserException(org.xmlpull.v1.XmlPullParserException)

Example 3 with NetworkRequest

use of android.net.NetworkRequest in project platform_frameworks_base by android.

the class ConnectivityService method pendingListenForNetwork.

@Override
public void pendingListenForNetwork(NetworkCapabilities networkCapabilities, PendingIntent operation) {
    checkNotNull(operation, "PendingIntent cannot be null.");
    if (!hasWifiNetworkListenPermission(networkCapabilities)) {
        enforceAccessPermission();
    }
    NetworkRequest networkRequest = new NetworkRequest(new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
    NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
    if (VDBG)
        log("pendingListenForNetwork for " + nri);
    mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
}
Also used : NetworkRequest(android.net.NetworkRequest) NetworkCapabilities(android.net.NetworkCapabilities)

Example 4 with NetworkRequest

use of android.net.NetworkRequest in project platform_frameworks_base by android.

the class ConnectivityService method requestNetwork.

@Override
public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities, Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
    final NetworkRequest.Type type = (networkCapabilities == null) ? NetworkRequest.Type.TRACK_DEFAULT : NetworkRequest.Type.REQUEST;
    // the system default network.
    if (type == NetworkRequest.Type.TRACK_DEFAULT) {
        networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
        enforceAccessPermission();
    } else {
        networkCapabilities = new NetworkCapabilities(networkCapabilities);
        enforceNetworkRequestPermissions(networkCapabilities);
        // TODO: this is incorrect. We mark the request as metered or not depending on the state
        // of the app when the request is filed, but we never change the request if the app
        // changes network state. http://b/29964605
        enforceMeteredApnPolicy(networkCapabilities);
    }
    ensureRequestableCapabilities(networkCapabilities);
    if (timeoutMs < 0) {
        throw new IllegalArgumentException("Bad timeout specified");
    }
    if (NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER.equals(networkCapabilities.getNetworkSpecifier())) {
        throw new IllegalArgumentException("Invalid network specifier - must not be '" + NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER + "'");
    }
    NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType, nextNetworkRequestId(), type);
    NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
    if (DBG)
        log("requestNetwork for " + nri);
    mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
    if (timeoutMs > 0) {
        mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST, nri), timeoutMs);
    }
    return networkRequest;
}
Also used : NetworkRequest(android.net.NetworkRequest) NetworkCapabilities(android.net.NetworkCapabilities)

Example 5 with NetworkRequest

use of android.net.NetworkRequest in project platform_frameworks_base by android.

the class ConnectivityService method handleRemoveNetworkRequest.

private void handleRemoveNetworkRequest(final NetworkRequestInfo nri, final int whichCallback) {
    final String logCallbackType = ConnectivityManager.getCallbackName(whichCallback);
    if (VDBG || (DBG && nri.request.isRequest())) {
        log("releasing " + nri.request + " (" + logCallbackType + ")");
    }
    nri.unlinkDeathRecipient();
    mNetworkRequests.remove(nri.request);
    synchronized (mUidToNetworkRequestCount) {
        int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
        if (requests < 1) {
            Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " + nri.mUid);
        } else if (requests == 1) {
            mUidToNetworkRequestCount.removeAt(mUidToNetworkRequestCount.indexOfKey(nri.mUid));
        } else {
            mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
        }
    }
    mNetworkRequestInfoLogs.log("RELEASE " + nri);
    if (nri.request.isRequest()) {
        boolean wasKept = false;
        NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
        if (nai != null) {
            boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
            nai.removeRequest(nri.request.requestId);
            if (VDBG) {
                log(" Removing from current network " + nai.name() + ", leaving " + nai.numNetworkRequests() + " requests.");
            }
            // If there are still lingered requests on this network, don't tear it down,
            // but resume lingering instead.
            updateLingerState(nai, SystemClock.elapsedRealtime());
            if (unneeded(nai, UnneededFor.TEARDOWN)) {
                if (DBG)
                    log("no live requests for " + nai.name() + "; disconnecting");
                teardownUnneededNetwork(nai);
            } else {
                wasKept = true;
            }
            mNetworkForRequestId.remove(nri.request.requestId);
            if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
                // Went from foreground to background.
                updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
            }
        }
        // network satisfying it, so this loop is wasteful
        for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
            if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
                Slog.wtf(TAG, "Request " + nri.request + " satisfied by " + otherNai.name() + ", but mNetworkAgentInfos says " + (nai != null ? nai.name() : "null"));
            }
        }
        // phantom disconnect for this type.
        if (nri.request.legacyType != TYPE_NONE && nai != null) {
            boolean doRemove = true;
            if (wasKept) {
                // same legacy type - if so, don't remove the nai
                for (int i = 0; i < nai.numNetworkRequests(); i++) {
                    NetworkRequest otherRequest = nai.requestAt(i);
                    if (otherRequest.legacyType == nri.request.legacyType && otherRequest.isRequest()) {
                        if (DBG)
                            log(" still have other legacy request - leaving");
                        doRemove = false;
                    }
                }
            }
            if (doRemove) {
                mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
            }
        }
        for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
            nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST, nri.request);
        }
    } else {
        // if this listen request applies and remove it.
        for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
            nai.removeRequest(nri.request.requestId);
            if (nri.request.networkCapabilities.hasSignalStrength() && nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
                updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
            }
        }
    }
    callCallbackForRequest(nri, null, whichCallback, 0);
}
Also used : NetworkAgentInfo(com.android.server.connectivity.NetworkAgentInfo) NetworkRequest(android.net.NetworkRequest) NetworkPolicyManager.uidRulesToString(android.net.NetworkPolicyManager.uidRulesToString)

Aggregations

NetworkRequest (android.net.NetworkRequest)158 NetworkCapabilities (android.net.NetworkCapabilities)48 SmallTest (android.test.suitebuilder.annotation.SmallTest)43 ConditionVariable (android.os.ConditionVariable)24 LargeTest (android.test.suitebuilder.annotation.LargeTest)21 RemoteException (android.os.RemoteException)20 NetworkCallback (android.net.ConnectivityManager.NetworkCallback)18 Network (android.net.Network)16 NetworkAgentInfo (com.android.server.connectivity.NetworkAgentInfo)15 LinkProperties (android.net.LinkProperties)14 ArrayList (java.util.ArrayList)9 ContentResolver (android.content.ContentResolver)8 HandlerThread (android.os.HandlerThread)8 MockContentResolver (android.test.mock.MockContentResolver)8 ConnectivityManager (android.net.ConnectivityManager)6 NetworkPolicyManager.uidRulesToString (android.net.NetworkPolicyManager.uidRulesToString)6 Intent (android.content.Intent)5 Bundle (android.os.Bundle)5 Message (android.os.Message)5 IBatteryStats (com.android.internal.app.IBatteryStats)5