Search in sources :

Example 21 with Network

use of android.net.Network in project android_frameworks_base by DirtyUnicorns.

the class ConnectivityServiceTest method testRequestBenchmark.

@SmallTest
public void testRequestBenchmark() throws Exception {
    // Benchmarks connecting and switching performance in the presence of a large number of
    // NetworkRequests.
    // 1. File NUM_REQUESTS requests.
    // 2. Have a network connect. Wait for NUM_REQUESTS onAvailable callbacks to fire.
    // 3. Have a new network connect and outscore the previous. Wait for NUM_REQUESTS onLosing
    //    and NUM_REQUESTS onAvailable callbacks to fire.
    // See how long it took.
    final int NUM_REQUESTS = 90;
    final NetworkRequest request = new NetworkRequest.Builder().clearCapabilities().build();
    final NetworkCallback[] callbacks = new NetworkCallback[NUM_REQUESTS];
    final CountDownLatch availableLatch = new CountDownLatch(NUM_REQUESTS);
    final CountDownLatch losingLatch = new CountDownLatch(NUM_REQUESTS);
    final int REGISTER_TIME_LIMIT_MS = 100;
    long startTime = System.currentTimeMillis();
    for (int i = 0; i < NUM_REQUESTS; i++) {
        callbacks[i] = new NetworkCallback() {

            @Override
            public void onAvailable(Network n) {
                availableLatch.countDown();
            }

            @Override
            public void onLosing(Network n, int t) {
                losingLatch.countDown();
            }
        };
        mCm.registerNetworkCallback(request, callbacks[i]);
    }
    long timeTaken = System.currentTimeMillis() - startTime;
    String msg = String.format("Register %d callbacks: %dms, acceptable %dms", NUM_REQUESTS, timeTaken, REGISTER_TIME_LIMIT_MS);
    Log.d(TAG, msg);
    assertTrue(msg, timeTaken < REGISTER_TIME_LIMIT_MS);
    final int CONNECT_TIME_LIMIT_MS = 30;
    mCellNetworkAgent = new MockNetworkAgent(TRANSPORT_CELLULAR);
    // Don't request that the network validate, because otherwise connect() will block until
    // the network gets NET_CAPABILITY_VALIDATED, after all the callbacks below have fired,
    // and we won't actually measure anything.
    mCellNetworkAgent.connect(false);
    startTime = System.currentTimeMillis();
    if (!availableLatch.await(CONNECT_TIME_LIMIT_MS, TimeUnit.MILLISECONDS)) {
        fail(String.format("Only dispatched %d/%d onAvailable callbacks in %dms", NUM_REQUESTS - availableLatch.getCount(), NUM_REQUESTS, CONNECT_TIME_LIMIT_MS));
    }
    timeTaken = System.currentTimeMillis() - startTime;
    Log.d(TAG, String.format("Connect, %d callbacks: %dms, acceptable %dms", NUM_REQUESTS, timeTaken, CONNECT_TIME_LIMIT_MS));
    final int SWITCH_TIME_LIMIT_MS = 30;
    mWiFiNetworkAgent = new MockNetworkAgent(TRANSPORT_WIFI);
    // Give wifi a high enough score that we'll linger cell when wifi comes up.
    mWiFiNetworkAgent.adjustScore(40);
    mWiFiNetworkAgent.connect(false);
    startTime = System.currentTimeMillis();
    if (!losingLatch.await(SWITCH_TIME_LIMIT_MS, TimeUnit.MILLISECONDS)) {
        fail(String.format("Only dispatched %d/%d onLosing callbacks in %dms", NUM_REQUESTS - losingLatch.getCount(), NUM_REQUESTS, SWITCH_TIME_LIMIT_MS));
    }
    timeTaken = System.currentTimeMillis() - startTime;
    Log.d(TAG, String.format("Linger, %d callbacks: %dms, acceptable %dms", NUM_REQUESTS, timeTaken, SWITCH_TIME_LIMIT_MS));
    final int UNREGISTER_TIME_LIMIT_MS = 10;
    startTime = System.currentTimeMillis();
    for (int i = 0; i < NUM_REQUESTS; i++) {
        mCm.unregisterNetworkCallback(callbacks[i]);
    }
    timeTaken = System.currentTimeMillis() - startTime;
    msg = String.format("Unregister %d callbacks: %dms, acceptable %dms", NUM_REQUESTS, timeTaken, UNREGISTER_TIME_LIMIT_MS);
    Log.d(TAG, msg);
    assertTrue(msg, timeTaken < UNREGISTER_TIME_LIMIT_MS);
}
Also used : Network(android.net.Network) NetworkRequest(android.net.NetworkRequest) CountDownLatch(java.util.concurrent.CountDownLatch) NetworkCallback(android.net.ConnectivityManager.NetworkCallback) SmallTest(android.test.suitebuilder.annotation.SmallTest)

Example 22 with Network

use of android.net.Network in project android_frameworks_base by DirtyUnicorns.

the class ConnectivityServiceTest method testAvoidBadWifi.

@SmallTest
public void testAvoidBadWifi() throws Exception {
    final ContentResolver cr = mServiceContext.getContentResolver();
    final WrappedAvoidBadWifiTracker tracker = mService.getAvoidBadWifiTracker();
    // Pretend we're on a carrier that restricts switching away from bad wifi.
    tracker.configRestrictsAvoidBadWifi = true;
    // File a request for cell to ensure it doesn't go down.
    final TestNetworkCallback cellNetworkCallback = new TestNetworkCallback();
    final NetworkRequest cellRequest = new NetworkRequest.Builder().addTransportType(TRANSPORT_CELLULAR).build();
    mCm.requestNetwork(cellRequest, cellNetworkCallback);
    TestNetworkCallback defaultCallback = new TestNetworkCallback();
    mCm.registerDefaultNetworkCallback(defaultCallback);
    NetworkRequest validatedWifiRequest = new NetworkRequest.Builder().addTransportType(TRANSPORT_WIFI).addCapability(NET_CAPABILITY_VALIDATED).build();
    TestNetworkCallback validatedWifiCallback = new TestNetworkCallback();
    mCm.registerNetworkCallback(validatedWifiRequest, validatedWifiCallback);
    Settings.Global.putInt(cr, Settings.Global.NETWORK_AVOID_BAD_WIFI, 0);
    tracker.reevaluate();
    // Bring up validated cell.
    mCellNetworkAgent = new MockNetworkAgent(TRANSPORT_CELLULAR);
    mCellNetworkAgent.connect(true);
    cellNetworkCallback.expectCallback(CallbackState.AVAILABLE, mCellNetworkAgent);
    defaultCallback.expectCallback(CallbackState.AVAILABLE, mCellNetworkAgent);
    Network cellNetwork = mCellNetworkAgent.getNetwork();
    // Bring up validated wifi.
    mWiFiNetworkAgent = new MockNetworkAgent(TRANSPORT_WIFI);
    mWiFiNetworkAgent.connect(true);
    defaultCallback.expectCallback(CallbackState.AVAILABLE, mWiFiNetworkAgent);
    validatedWifiCallback.expectCallback(CallbackState.AVAILABLE, mWiFiNetworkAgent);
    Network wifiNetwork = mWiFiNetworkAgent.getNetwork();
    // Fail validation on wifi.
    mWiFiNetworkAgent.getWrappedNetworkMonitor().gen204ProbeResult = 599;
    mCm.reportNetworkConnectivity(wifiNetwork, false);
    validatedWifiCallback.expectCallback(CallbackState.LOST, mWiFiNetworkAgent);
    // Because avoid bad wifi is off, we don't switch to cellular.
    defaultCallback.assertNoCallback();
    assertFalse(mCm.getNetworkCapabilities(wifiNetwork).hasCapability(NET_CAPABILITY_VALIDATED));
    assertTrue(mCm.getNetworkCapabilities(cellNetwork).hasCapability(NET_CAPABILITY_VALIDATED));
    assertEquals(mCm.getActiveNetwork(), wifiNetwork);
    // Simulate switching to a carrier that does not restrict avoiding bad wifi, and expect
    // that we switch back to cell.
    tracker.configRestrictsAvoidBadWifi = false;
    tracker.reevaluate();
    defaultCallback.expectCallback(CallbackState.AVAILABLE, mCellNetworkAgent);
    assertEquals(mCm.getActiveNetwork(), cellNetwork);
    // Switch back to a restrictive carrier.
    tracker.configRestrictsAvoidBadWifi = true;
    tracker.reevaluate();
    defaultCallback.expectCallback(CallbackState.AVAILABLE, mWiFiNetworkAgent);
    assertEquals(mCm.getActiveNetwork(), wifiNetwork);
    // Simulate the user selecting "switch" on the dialog, and check that we switch to cell.
    mCm.setAvoidUnvalidated(wifiNetwork);
    defaultCallback.expectCallback(CallbackState.AVAILABLE, mCellNetworkAgent);
    assertFalse(mCm.getNetworkCapabilities(wifiNetwork).hasCapability(NET_CAPABILITY_VALIDATED));
    assertTrue(mCm.getNetworkCapabilities(cellNetwork).hasCapability(NET_CAPABILITY_VALIDATED));
    assertEquals(mCm.getActiveNetwork(), cellNetwork);
    // Disconnect and reconnect wifi to clear the one-time switch above.
    mWiFiNetworkAgent.disconnect();
    mWiFiNetworkAgent = new MockNetworkAgent(TRANSPORT_WIFI);
    mWiFiNetworkAgent.connect(true);
    defaultCallback.expectCallback(CallbackState.AVAILABLE, mWiFiNetworkAgent);
    validatedWifiCallback.expectCallback(CallbackState.AVAILABLE, mWiFiNetworkAgent);
    wifiNetwork = mWiFiNetworkAgent.getNetwork();
    // Fail validation on wifi and expect the dialog to appear.
    mWiFiNetworkAgent.getWrappedNetworkMonitor().gen204ProbeResult = 599;
    mCm.reportNetworkConnectivity(wifiNetwork, false);
    validatedWifiCallback.expectCallback(CallbackState.LOST, mWiFiNetworkAgent);
    // Simulate the user selecting "switch" and checking the don't ask again checkbox.
    Settings.Global.putInt(cr, Settings.Global.NETWORK_AVOID_BAD_WIFI, 1);
    tracker.reevaluate();
    // We now switch to cell.
    defaultCallback.expectCallback(CallbackState.AVAILABLE, mCellNetworkAgent);
    assertFalse(mCm.getNetworkCapabilities(wifiNetwork).hasCapability(NET_CAPABILITY_VALIDATED));
    assertTrue(mCm.getNetworkCapabilities(cellNetwork).hasCapability(NET_CAPABILITY_VALIDATED));
    assertEquals(mCm.getActiveNetwork(), cellNetwork);
    // Simulate the user turning the cellular fallback setting off and then on.
    // We switch to wifi and then to cell.
    Settings.Global.putString(cr, Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
    tracker.reevaluate();
    defaultCallback.expectCallback(CallbackState.AVAILABLE, mWiFiNetworkAgent);
    assertEquals(mCm.getActiveNetwork(), wifiNetwork);
    Settings.Global.putInt(cr, Settings.Global.NETWORK_AVOID_BAD_WIFI, 1);
    tracker.reevaluate();
    defaultCallback.expectCallback(CallbackState.AVAILABLE, mCellNetworkAgent);
    assertEquals(mCm.getActiveNetwork(), cellNetwork);
    // If cell goes down, we switch to wifi.
    mCellNetworkAgent.disconnect();
    defaultCallback.expectCallback(CallbackState.LOST, mCellNetworkAgent);
    defaultCallback.expectCallback(CallbackState.AVAILABLE, mWiFiNetworkAgent);
    validatedWifiCallback.assertNoCallback();
    mCm.unregisterNetworkCallback(cellNetworkCallback);
    mCm.unregisterNetworkCallback(validatedWifiCallback);
    mCm.unregisterNetworkCallback(defaultCallback);
}
Also used : Network(android.net.Network) NetworkRequest(android.net.NetworkRequest) ContentResolver(android.content.ContentResolver) MockContentResolver(android.test.mock.MockContentResolver) SmallTest(android.test.suitebuilder.annotation.SmallTest)

Example 23 with Network

use of android.net.Network in project android_frameworks_base by DirtyUnicorns.

the class CaptivePortalLoginActivity method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mCm = ConnectivityManager.from(this);
    mNetwork = getIntent().getParcelableExtra(ConnectivityManager.EXTRA_NETWORK);
    mCaptivePortal = getIntent().getParcelableExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL);
    mUserAgent = getIntent().getParcelableExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL_USER_AGENT);
    mUrl = getUrl();
    if (mUrl == null) {
        // getUrl() failed to parse the url provided in the intent: bail out in a way that
        // at least provides network access.
        done(Result.WANTED_AS_IS);
        return;
    }
    if (DBG) {
        Log.d(TAG, String.format("onCreate for %s", mUrl.toString()));
    }
    // Also initializes proxy system properties.
    mCm.bindProcessToNetwork(mNetwork);
    // Proxy system properties must be initialized before setContentView is called because
    // setContentView initializes the WebView logic which in turn reads the system properties.
    setContentView(R.layout.activity_captive_portal_login);
    getActionBar().setDisplayShowHomeEnabled(false);
    // Exit app if Network disappears.
    final NetworkCapabilities networkCapabilities = mCm.getNetworkCapabilities(mNetwork);
    if (networkCapabilities == null) {
        finishAndRemoveTask();
        return;
    }
    mNetworkCallback = new NetworkCallback() {

        @Override
        public void onLost(Network lostNetwork) {
            if (mNetwork.equals(lostNetwork))
                done(Result.UNWANTED);
        }
    };
    final NetworkRequest.Builder builder = new NetworkRequest.Builder();
    for (int transportType : networkCapabilities.getTransportTypes()) {
        builder.addTransportType(transportType);
    }
    mCm.registerNetworkCallback(builder.build(), mNetworkCallback);
    final WebView myWebView = (WebView) findViewById(R.id.webview);
    myWebView.clearCache(true);
    WebSettings webSettings = myWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
    webSettings.setUseWideViewPort(true);
    webSettings.setLoadWithOverviewMode(true);
    webSettings.setSupportZoom(true);
    webSettings.setBuiltInZoomControls(true);
    webSettings.setDisplayZoomControls(false);
    mWebViewClient = new MyWebViewClient();
    myWebView.setWebViewClient(mWebViewClient);
    myWebView.setWebChromeClient(new MyWebChromeClient());
    // Start initial page load so WebView finishes loading proxy settings.
    // Actual load of mUrl is initiated by MyWebViewClient.
    myWebView.loadData("", "text/html", null);
}
Also used : WebSettings(android.webkit.WebSettings) Network(android.net.Network) NetworkRequest(android.net.NetworkRequest) WebView(android.webkit.WebView) NetworkCapabilities(android.net.NetworkCapabilities) NetworkCallback(android.net.ConnectivityManager.NetworkCallback)

Example 24 with Network

use of android.net.Network in project kdeconnect-android by KDE.

the class NetworkHelper method isOnMobileNetwork.

public static boolean isOnMobileNetwork(Context context) {
    if (context == null || android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.LOLLIPOP) {
        //No good way to know it
        return false;
    }
    boolean mobile = false;
    final ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    Network[] networks = connMgr.getAllNetworks();
    for (Network network : networks) {
        NetworkInfo info = connMgr.getNetworkInfo(network);
        if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
            mobile = info.isConnected();
            continue;
        }
        Log.e(info.getTypeName(), "" + info.isAvailable());
        //We are connected to at least one non-mobile network
        if (info.isAvailable())
            return false;
    }
    return mobile;
}
Also used : NetworkInfo(android.net.NetworkInfo) ConnectivityManager(android.net.ConnectivityManager) Network(android.net.Network)

Example 25 with Network

use of android.net.Network in project android_frameworks_base by AOSPA.

the class OSUManager method wnmRemediate.

// !!! Consistently check passpoint match.
// !!! Convert to a one-thread thread-pool
public void wnmRemediate(long bssid, String url, PasspointMatch match) throws IOException, SAXException {
    WifiConfiguration config = mWifiNetworkAdapter.getActiveWifiConfig();
    HomeSP homeSP = MOManager.buildSP(config.getMoTree());
    if (homeSP == null) {
        throw new IOException("Remediation request for unidentified Passpoint network " + config.networkId);
    }
    Network network = mWifiNetworkAdapter.getCurrentNetwork();
    if (network == null) {
        throw new IOException("Failed to determine current network");
    }
    WifiInfo wifiInfo = mWifiNetworkAdapter.getConnectionInfo();
    if (wifiInfo == null || Utils.parseMac(wifiInfo.getBSSID()) != bssid) {
        throw new IOException("Mismatching BSSID");
    }
    Log.d(TAG, "WNM Remediation on " + network.netId + " FQDN " + homeSP.getFQDN());
    doRemediate(url, network, homeSP, false);
}
Also used : HomeSP(com.android.hotspot2.pps.HomeSP) WifiConfiguration(android.net.wifi.WifiConfiguration) Network(android.net.Network) IOException(java.io.IOException) WifiInfo(android.net.wifi.WifiInfo)

Aggregations

Network (android.net.Network)90 SmallTest (android.test.suitebuilder.annotation.SmallTest)28 NetworkAgentInfo (com.android.server.connectivity.NetworkAgentInfo)25 NetworkCapabilities (android.net.NetworkCapabilities)22 NetworkInfo (android.net.NetworkInfo)17 LinkProperties (android.net.LinkProperties)16 NetworkRequest (android.net.NetworkRequest)16 NetworkCallback (android.net.ConnectivityManager.NetworkCallback)11 ConnectivityManager (android.net.ConnectivityManager)9 InetAddress (java.net.InetAddress)6 Test (org.junit.Test)6 Nullable (android.annotation.Nullable)5 NetworkMisc (android.net.NetworkMisc)5 NetworkState (android.net.NetworkState)5 WifiConfiguration (android.net.wifi.WifiConfiguration)5 WifiInfo (android.net.wifi.WifiInfo)5 ConditionVariable (android.os.ConditionVariable)5 WebSettings (android.webkit.WebSettings)5 HomeSP (com.android.hotspot2.pps.HomeSP)5 LegacyVpnInfo (com.android.internal.net.LegacyVpnInfo)5