Search in sources :

Example 46 with Network

use of android.net.Network in project mobile-center-sdk-android by Microsoft.

the class NetworkStateHelper method reopen.

/**
 * Make this helper active again after closing.
 */
public void reopen() {
    try {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            /* Build query to get a working network listener. */
            NetworkRequest.Builder request = new NetworkRequest.Builder();
            request.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                request.addCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);
            }
            mNetworkCallback = new ConnectivityManager.NetworkCallback() {

                @Override
                public void onAvailable(Network network) {
                    Log.d(AppCenter.LOG_TAG, "Network available netId: " + network);
                    mAvailableNetworks.add(network);
                    Log.d(AppCenter.LOG_TAG, "Available networks netIds: " + mAvailableNetworks);
                    /*
                         * Trigger event only once if we gain a new network while one was already
                         * available. Special logic is handled in network lost events.
                         */
                    if (mAvailableNetworks.size() == 1) {
                        notifyNetworkStateUpdated(true);
                    }
                }

                @Override
                public void onLost(Network network) {
                    /*
                        * We will have WIFI network available event before we lose mobile network.
                        * Pending calls just before the switch might take a while to fail.
                        * When we lose a network, but have another one available, just simulate network
                        * down then up again to properly reset pending calls so that they are reliable
                        * and fast. This notification scheme is similar to the old connectivity receiver
                        * implementation.
                        */
                    Log.d(AppCenter.LOG_TAG, "Network lost netId: " + network);
                    mAvailableNetworks.remove(network);
                    Log.d(AppCenter.LOG_TAG, "Available networks netIds: " + mAvailableNetworks);
                    notifyNetworkStateUpdated(false);
                    if (!mAvailableNetworks.isEmpty()) {
                        notifyNetworkStateUpdated(true);
                    }
                }
            };
            // noinspection ConstantConditions
            mConnectivityManager.registerNetworkCallback(request.build(), mNetworkCallback);
        } else {
            updateNetworkType();
            mConnectivityReceiver = new ConnectivityReceiver();
            mContext.registerReceiver(mConnectivityReceiver, new IntentFilter(CONNECTIVITY_ACTION));
        }
    } catch (RuntimeException e) {
        /*
             * Can be security exception if permission missing or sometimes another runtime exception
             * on some customized firmwares.
             */
        AppCenterLog.error(LOG_TAG, "Cannot access network state information", e);
    }
}
Also used : IntentFilter(android.content.IntentFilter) ConnectivityManager(android.net.ConnectivityManager) Network(android.net.Network) NetworkRequest(android.net.NetworkRequest)

Example 47 with Network

use of android.net.Network in project mobile-center-sdk-android by Microsoft.

the class NetworkStateHelperTestFromLollipop method listenNetwork.

@Test
@SuppressWarnings("deprecation")
public void listenNetwork() {
    NetworkStateHelper helper = new NetworkStateHelper(mContext);
    ArgumentCaptor<ConnectivityManager.NetworkCallback> callback = ArgumentCaptor.forClass(ConnectivityManager.NetworkCallback.class);
    verify(mConnectivityManager).registerNetworkCallback(any(NetworkRequest.class), callback.capture());
    NetworkStateHelper.Listener listener = mock(NetworkStateHelper.Listener.class);
    helper.addListener(listener);
    /* Initial state is down, if state does not change, no callback. */
    verify(listener, never()).onNetworkStateUpdated(anyBoolean());
    /* Change state to up, say WIFI. */
    Network network = mock(Network.class);
    callback.getValue().onAvailable(network);
    verify(listener).onNetworkStateUpdated(true);
    verify(listener, never()).onNetworkStateUpdated(false);
    assertTrue(helper.isNetworkConnected());
    /* Change to say, Mobile. */
    helper.removeListener(listener);
    NetworkStateHelper.Listener listener2 = mock(NetworkStateHelper.Listener.class);
    helper.addListener(listener2);
    callback.getValue().onLost(network);
    network = mock(Network.class);
    callback.getValue().onAvailable(network);
    verify(listener2).onNetworkStateUpdated(false);
    verify(listener2).onNetworkStateUpdated(true);
    assertTrue(helper.isNetworkConnected());
    /* Make new network available before we lost the previous one. */
    helper.removeListener(listener2);
    NetworkStateHelper.Listener listener3 = mock(NetworkStateHelper.Listener.class);
    helper.addListener(listener3);
    Network network2 = mock(Network.class);
    callback.getValue().onAvailable(network2);
    assertTrue(helper.isNetworkConnected());
    /* The callbacks are triggered only when losing previous network. */
    verify(listener3, never()).onNetworkStateUpdated(anyBoolean());
    callback.getValue().onLost(network);
    verify(listener3).onNetworkStateUpdated(false);
    verify(listener3).onNetworkStateUpdated(true);
    assertTrue(helper.isNetworkConnected());
    /* Lose second network. */
    callback.getValue().onLost(network2);
    verify(listener3, times(2)).onNetworkStateUpdated(false);
    assertFalse(helper.isNetworkConnected());
    /* Make it connected again before closing with no listener. */
    helper.removeListener(listener3);
    network = mock(Network.class);
    callback.getValue().onAvailable(network);
    verifyNoMoreInteractions(listener3);
    assertTrue(helper.isNetworkConnected());
    /* Close and verify interactions. This will also reset to disconnected. */
    helper.close();
    assertFalse(helper.isNetworkConnected());
    verify(mConnectivityManager).unregisterNetworkCallback(callback.getValue());
    /* Reopening will not restore removed listeners by close. */
    helper.reopen();
    assertFalse(helper.isNetworkConnected());
    network = mock(Network.class);
    callback.getValue().onAvailable(network);
    assertTrue(helper.isNetworkConnected());
    verify(mConnectivityManager, times(2)).registerNetworkCallback(any(NetworkRequest.class), any(ConnectivityManager.NetworkCallback.class));
    /* Check no extra listener calls. */
    verifyNoMoreInteractions(listener);
    verifyNoMoreInteractions(listener2);
    verifyNoMoreInteractions(listener3);
    /* Verify we didn't try to use older APIs after Lollipop on newer devices. */
    verify(mContext, never()).registerReceiver(any(BroadcastReceiver.class), any(IntentFilter.class));
    verify(mContext, never()).unregisterReceiver(any(BroadcastReceiver.class));
    verify(mConnectivityManager, never()).getActiveNetworkInfo();
}
Also used : IntentFilter(android.content.IntentFilter) ConnectivityManager(android.net.ConnectivityManager) Network(android.net.Network) NetworkRequest(android.net.NetworkRequest) BroadcastReceiver(android.content.BroadcastReceiver) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 48 with Network

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

the class ConnectivityServiceTest method testWaitForIdle.

@SmallTest
public void testWaitForIdle() {
    // Causes the test to take about 200ms on bullhead-eng.
    final int attempts = 50;
    // Tests that waitForIdle returns immediately if the service is already idle.
    for (int i = 0; i < attempts; i++) {
        mService.waitForIdle();
    }
    // Bring up a network that we can use to send messages to ConnectivityService.
    ConditionVariable cv = waitForConnectivityBroadcasts(1);
    mWiFiNetworkAgent = new MockNetworkAgent(TRANSPORT_WIFI);
    mWiFiNetworkAgent.connect(false);
    waitFor(cv);
    Network n = mWiFiNetworkAgent.getNetwork();
    assertNotNull(n);
    // Tests that calling waitForIdle waits for messages to be processed.
    for (int i = 0; i < attempts; i++) {
        mWiFiNetworkAgent.setSignalStrength(i);
        mService.waitForIdle();
        assertEquals(i, mCm.getNetworkCapabilities(n).getSignalStrength());
    }
}
Also used : ConditionVariable(android.os.ConditionVariable) Network(android.net.Network) SmallTest(android.test.suitebuilder.annotation.SmallTest)

Example 49 with Network

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

the class ConnectivityServiceTest method verifyThatNotWaitingForIdleCausesRaceConditions.

// This test has an inherent race condition in it, and cannot be enabled for continuous testing
// or presubmit tests. It is kept for manual runs and documentation purposes.
public void verifyThatNotWaitingForIdleCausesRaceConditions() {
    // Bring up a network that we can use to send messages to ConnectivityService.
    ConditionVariable cv = waitForConnectivityBroadcasts(1);
    mWiFiNetworkAgent = new MockNetworkAgent(TRANSPORT_WIFI);
    mWiFiNetworkAgent.connect(false);
    waitFor(cv);
    Network n = mWiFiNetworkAgent.getNetwork();
    assertNotNull(n);
    // Ensure that not calling waitForIdle causes a race condition.
    // Causes the test to take about 200ms on bullhead-eng.
    final int attempts = 50;
    for (int i = 0; i < attempts; i++) {
        mWiFiNetworkAgent.setSignalStrength(i);
        if (i != mCm.getNetworkCapabilities(n).getSignalStrength()) {
            // We hit a race condition, as expected. Pass the test.
            return;
        }
    }
    // No race? There is a bug in this test.
    fail("expected race condition at least once in " + attempts + " attempts");
}
Also used : ConditionVariable(android.os.ConditionVariable) Network(android.net.Network)

Example 50 with Network

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

the class NetdEventListenerServiceTest method testConcurrentBatchesAndNetworkLoss.

@SmallTest
public void testConcurrentBatchesAndNetworkLoss() throws Exception {
    logAsync(105, LATENCIES);
    Thread.sleep(10L);
    // call onLost() asynchronously to logAsync's onDnsEvent() calls.
    mCallbackCaptor.getValue().onLost(new Network(105));
    // do not verify unpredictable batch
    verify(mLog, timeout(500).times(1)).log(any());
}
Also used : Network(android.net.Network) SmallTest(android.test.suitebuilder.annotation.SmallTest)

Aggregations

Network (android.net.Network)92 SmallTest (android.test.suitebuilder.annotation.SmallTest)28 NetworkAgentInfo (com.android.server.connectivity.NetworkAgentInfo)25 NetworkCapabilities (android.net.NetworkCapabilities)22 NetworkRequest (android.net.NetworkRequest)18 NetworkInfo (android.net.NetworkInfo)17 LinkProperties (android.net.LinkProperties)16 ConnectivityManager (android.net.ConnectivityManager)11 NetworkCallback (android.net.ConnectivityManager.NetworkCallback)11 Test (org.junit.Test)7 InetAddress (java.net.InetAddress)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