Search in sources :

Example 26 with NetworkCallback

use of android.net.ConnectivityManager.NetworkCallback in project android_frameworks_base by crdroidandroid.

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 27 with NetworkCallback

use of android.net.ConnectivityManager.NetworkCallback in project android_frameworks_base by crdroidandroid.

the class ConnectivityServiceTest method tryNetworkFactoryRequests.

private void tryNetworkFactoryRequests(int capability) throws Exception {
    // Verify NOT_RESTRICTED is set appropriately
    final NetworkCapabilities nc = new NetworkRequest.Builder().addCapability(capability).build().networkCapabilities;
    if (capability == NET_CAPABILITY_CBS || capability == NET_CAPABILITY_DUN || capability == NET_CAPABILITY_EIMS || capability == NET_CAPABILITY_FOTA || capability == NET_CAPABILITY_IA || capability == NET_CAPABILITY_IMS || capability == NET_CAPABILITY_RCS || capability == NET_CAPABILITY_XCAP) {
        assertFalse(nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED));
    } else {
        assertTrue(nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED));
    }
    NetworkCapabilities filter = new NetworkCapabilities();
    filter.addCapability(capability);
    final HandlerThread handlerThread = new HandlerThread("testNetworkFactoryRequests");
    handlerThread.start();
    final MockNetworkFactory testFactory = new MockNetworkFactory(handlerThread.getLooper(), mServiceContext, "testFactory", filter);
    testFactory.setScoreFilter(40);
    ConditionVariable cv = testFactory.getNetworkStartedCV();
    testFactory.expectAddRequests(1);
    testFactory.register();
    testFactory.waitForNetworkRequests(1);
    int expectedRequestCount = 1;
    NetworkCallback networkCallback = null;
    // add one.
    if (capability != NET_CAPABILITY_INTERNET) {
        assertFalse(testFactory.getMyStartRequested());
        NetworkRequest request = new NetworkRequest.Builder().addCapability(capability).build();
        networkCallback = new NetworkCallback();
        testFactory.expectAddRequests(1);
        mCm.requestNetwork(request, networkCallback);
        expectedRequestCount++;
        testFactory.waitForNetworkRequests(expectedRequestCount);
    }
    waitFor(cv);
    assertEquals(expectedRequestCount, testFactory.getMyRequestCount());
    assertTrue(testFactory.getMyStartRequested());
    // Now bring in a higher scored network.
    MockNetworkAgent testAgent = new MockNetworkAgent(TRANSPORT_CELLULAR);
    // Rather than create a validated network which complicates things by registering it's
    // own NetworkRequest during startup, just bump up the score to cancel out the
    // unvalidated penalty.
    testAgent.adjustScore(40);
    cv = testFactory.getNetworkStoppedCV();
    // When testAgent connects, ConnectivityService will re-send us all current requests with
    // the new score. There are expectedRequestCount such requests, and we must wait for all of
    // them.
    testFactory.expectAddRequests(expectedRequestCount);
    testAgent.connect(false);
    testAgent.addCapability(capability);
    waitFor(cv);
    testFactory.waitForNetworkRequests(expectedRequestCount);
    assertFalse(testFactory.getMyStartRequested());
    // Bring in a bunch of requests.
    testFactory.expectAddRequests(10);
    assertEquals(expectedRequestCount, testFactory.getMyRequestCount());
    ConnectivityManager.NetworkCallback[] networkCallbacks = new ConnectivityManager.NetworkCallback[10];
    for (int i = 0; i < networkCallbacks.length; i++) {
        networkCallbacks[i] = new ConnectivityManager.NetworkCallback();
        NetworkRequest.Builder builder = new NetworkRequest.Builder();
        builder.addCapability(capability);
        mCm.requestNetwork(builder.build(), networkCallbacks[i]);
    }
    testFactory.waitForNetworkRequests(10 + expectedRequestCount);
    assertFalse(testFactory.getMyStartRequested());
    // Remove the requests.
    testFactory.expectRemoveRequests(10);
    for (int i = 0; i < networkCallbacks.length; i++) {
        mCm.unregisterNetworkCallback(networkCallbacks[i]);
    }
    testFactory.waitForNetworkRequests(expectedRequestCount);
    assertFalse(testFactory.getMyStartRequested());
    // Drop the higher scored network.
    cv = testFactory.getNetworkStartedCV();
    testAgent.disconnect();
    waitFor(cv);
    assertEquals(expectedRequestCount, testFactory.getMyRequestCount());
    assertTrue(testFactory.getMyStartRequested());
    testFactory.unregister();
    if (networkCallback != null)
        mCm.unregisterNetworkCallback(networkCallback);
    handlerThread.quit();
}
Also used : ConnectivityManager(android.net.ConnectivityManager) NetworkRequest(android.net.NetworkRequest) NetworkCallback(android.net.ConnectivityManager.NetworkCallback) NetworkCapabilities(android.net.NetworkCapabilities) NetworkCallback(android.net.ConnectivityManager.NetworkCallback) ConditionVariable(android.os.ConditionVariable) HandlerThread(android.os.HandlerThread)

Example 28 with NetworkCallback

use of android.net.ConnectivityManager.NetworkCallback in project android_frameworks_base by crdroidandroid.

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 29 with NetworkCallback

use of android.net.ConnectivityManager.NetworkCallback in project android_packages_apps_Settings by LineageOS.

the class WifiNoInternetDialog method onCreate.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    final Intent intent = getIntent();
    if (intent == null || !isKnownAction(intent) || !"netId".equals(intent.getScheme())) {
        Log.e(TAG, "Unexpected intent " + intent + ", exiting");
        finish();
        return;
    }
    mAction = intent.getAction();
    try {
        mNetwork = new Network(Integer.parseInt(intent.getData().getSchemeSpecificPart()));
    } catch (NullPointerException | NumberFormatException e) {
        mNetwork = null;
    }
    if (mNetwork == null) {
        Log.e(TAG, "Can't determine network from '" + intent.getData() + "' , exiting");
        finish();
        return;
    }
    // TODO: add a registerNetworkCallback(Network network, NetworkCallback networkCallback) and
    // simplify this.
    final NetworkRequest request = new NetworkRequest.Builder().clearCapabilities().build();
    mNetworkCallback = new NetworkCallback() {

        @Override
        public void onLost(Network network) {
            // Close the dialog if the network disconnects.
            if (mNetwork.equals(network)) {
                Log.d(TAG, "Network " + mNetwork + " disconnected");
                finish();
            }
        }

        @Override
        public void onCapabilitiesChanged(Network network, NetworkCapabilities nc) {
            // Close the dialog if the network validates.
            if (mNetwork.equals(network) && nc.hasCapability(NET_CAPABILITY_VALIDATED)) {
                Log.d(TAG, "Network " + mNetwork + " validated");
                finish();
            }
        }
    };
    mCM = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    mCM.registerNetworkCallback(request, mNetworkCallback);
    final NetworkInfo ni = mCM.getNetworkInfo(mNetwork);
    if (ni == null || !ni.isConnectedOrConnecting()) {
        Log.d(TAG, "Network " + mNetwork + " is not connected: " + ni);
        finish();
        return;
    }
    mNetworkName = ni.getExtraInfo();
    if (mNetworkName != null) {
        // Remove double quotes
        mNetworkName = mNetworkName.replaceAll("^\"|\"$", "");
    }
    createDialog();
}
Also used : NetworkInfo(android.net.NetworkInfo) Network(android.net.Network) NetworkRequest(android.net.NetworkRequest) Intent(android.content.Intent) NetworkCapabilities(android.net.NetworkCapabilities) NetworkCallback(android.net.ConnectivityManager.NetworkCallback)

Example 30 with NetworkCallback

use of android.net.ConnectivityManager.NetworkCallback in project platform_frameworks_base by android.

the class ConnectivityServiceTest method testNoMutableNetworkRequests.

@SmallTest
public void testNoMutableNetworkRequests() throws Exception {
    PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, new Intent("a"), 0);
    NetworkRequest.Builder builder = new NetworkRequest.Builder();
    builder.addCapability(NET_CAPABILITY_VALIDATED);
    try {
        mCm.requestNetwork(builder.build(), new NetworkCallback());
        fail();
    } catch (IllegalArgumentException expected) {
    }
    try {
        mCm.requestNetwork(builder.build(), pendingIntent);
        fail();
    } catch (IllegalArgumentException expected) {
    }
    builder = new NetworkRequest.Builder();
    builder.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
    try {
        mCm.requestNetwork(builder.build(), new NetworkCallback());
        fail();
    } catch (IllegalArgumentException expected) {
    }
    try {
        mCm.requestNetwork(builder.build(), pendingIntent);
        fail();
    } catch (IllegalArgumentException expected) {
    }
}
Also used : NetworkRequest(android.net.NetworkRequest) PendingIntent(android.app.PendingIntent) Intent(android.content.Intent) PendingIntent(android.app.PendingIntent) NetworkCallback(android.net.ConnectivityManager.NetworkCallback) SmallTest(android.test.suitebuilder.annotation.SmallTest)

Aggregations

NetworkCallback (android.net.ConnectivityManager.NetworkCallback)35 NetworkRequest (android.net.NetworkRequest)32 Network (android.net.Network)18 Intent (android.content.Intent)17 NetworkCapabilities (android.net.NetworkCapabilities)16 SmallTest (android.test.suitebuilder.annotation.SmallTest)13 PendingIntent (android.app.PendingIntent)8 NetworkInfo (android.net.NetworkInfo)7 WebSettings (android.webkit.WebSettings)5 WebView (android.webkit.WebView)5 ConnectivityManager (android.net.ConnectivityManager)4 ConditionVariable (android.os.ConditionVariable)4 HandlerThread (android.os.HandlerThread)4 ArrayList (java.util.ArrayList)4 CountDownLatch (java.util.concurrent.CountDownLatch)4 LargeTest (android.test.suitebuilder.annotation.LargeTest)3 Test (org.junit.Test)2