FileDocCategorySizeDatePackage
ConnectivityManagerTestBase.javaAPI DocAndroid 5.1 API19124Thu Mar 12 22:22:12 GMT 2015com.android.connectivitymanagertest

ConnectivityManagerTestBase

public class ConnectivityManagerTestBase extends android.test.InstrumentationTestCase
Base InstrumentationTestCase for Connectivity Manager (CM) test suite It registers connectivity manager broadcast and WiFi broadcast to provide network connectivity information, also provides a set of utility functions to modify and verify connectivity states. A CM test case should extend this base class.

Fields Summary
private static final String[]
PING_HOST_LIST
protected static final int
WAIT_FOR_SCAN_RESULT
protected static final int
WIFI_SCAN_TIMEOUT
protected static final int
SHORT_TIMEOUT
protected static final long
LONG_TIMEOUT
protected static final long
WIFI_CONNECTION_TIMEOUT
protected static final long
WIFI_STOP_START_INTERVAL
protected static final long
PING_TIMER
protected static final int
SUCCESS
protected static final int
FAILURE
protected static final int
INIT
protected final String
mLogTag
private ConnectivityReceiver
mConnectivityReceiver
private WifiReceiver
mWifiReceiver
private long
mLastConnectivityChangeTime
protected android.net.ConnectivityManager
mCm
private android.content.Context
mContext
protected List
mLastScanResult
protected Object
mWifiScanResultLock
public android.net.wifi.WifiManager
mWifiManager
Constructors Summary
public ConnectivityManagerTestBase(String logTag)


       
        super();
        mLogTag = logTag;
    
Methods Summary
protected booleancheckNetworkConnectivity()

        assertTrue("no active network connection", waitForActiveNetworkConnection(LONG_TIMEOUT));
        return pingTest();
    
protected booleanconnectToWifi(java.lang.String ssid, java.lang.String password)
Associate the device to given SSID If the device is already associated with a WiFi, disconnect and forget it, We don't verify whether the connection is successful or not, leave this to the test

        WifiConfiguration config;
        if (password == null) {
            config = WifiConfigurationHelper.createOpenConfig(ssid);
        } else {
            config = WifiConfigurationHelper.createPskConfig(ssid, password);
        }
        return connectToWifiWithConfiguration(config);
    
protected voidconnectToWifi(android.net.wifi.WifiConfiguration config)
Connect to the provided Wi-Fi network

param
config is the network configuration
throws
AssertionError if fails to associate and connect to wifi ap

        // step 1: connect to the test access point
        assertTrue("failed to associate with " + config.SSID,
                connectToWifiWithConfiguration(config));

        // step 2: verify Wifi state and network state;
        assertTrue("wifi state not connected with " + config.SSID,
                waitForNetworkState(ConnectivityManager.TYPE_WIFI,
                State.CONNECTED, WIFI_CONNECTION_TIMEOUT));

        // step 3: verify the current connected network is the given SSID
        assertNotNull("no active wifi info", mWifiManager.getConnectionInfo());
        assertEquals("SSID mismatch", config.SSID, mWifiManager.getConnectionInfo().getSSID());
    
protected booleanconnectToWifiWithConfiguration(android.net.wifi.WifiConfiguration config)
Connect to Wi-Fi with the given configuration. Note the SSID in the configuration is pure string, we need to convert it to quoted string.

        // If Wifi is not enabled, enable it
        if (!mWifiManager.isWifiEnabled()) {
            logv("Wifi is not enabled, enable it");
            mWifiManager.setWifiEnabled(true);
            // wait for the wifi state change before start scanning.
            if (!waitForWifiState(WifiManager.WIFI_STATE_ENABLED, LONG_TIMEOUT)) {
                logv("wait for WIFI_STATE_ENABLED failed");
                return false;
            }
        }

        // Save network configuration and connect to network without scanning
        mWifiManager.connect(config,
            new WifiManager.ActionListener() {
                @Override
                public void onSuccess() {
                }

                @Override
                public void onFailure(int reason) {
                    logv("connect failure " + reason);
                }
            });
        return true;
    
protected static java.lang.StringconvertToQuotedString(java.lang.String string)

        return "\"" + string + "\"";
    
protected booleandisableWifi()
Disable Wifi

return
true if Wifi is disabled successfully

        return mWifiManager.setWifiEnabled(false);
    
protected booleandisconnectAP()

        // remove saved networks
        if (!mWifiManager.isWifiEnabled()) {
            logv("Enabled wifi before remove configured networks");
            mWifiManager.setWifiEnabled(true);
            SystemClock.sleep(SHORT_TIMEOUT);
        }

        List<WifiConfiguration> wifiConfigList = mWifiManager.getConfiguredNetworks();
        if (wifiConfigList == null) {
            logv("no configuration list is null");
            return true;
        }
        logv("size of wifiConfigList: " + wifiConfigList.size());
        for (WifiConfiguration wifiConfig: wifiConfigList) {
            logv("remove wifi configuration: " + wifiConfig.networkId);
            int netId = wifiConfig.networkId;
            mWifiManager.forget(netId, new WifiManager.ActionListener() {
                    @Override
                    public void onSuccess() {
                    }

                    @Override
                    public void onFailure(int reason) {
                        logv("Failed to forget " + reason);
                    }
                });
        }
        return true;
    
protected booleanenableWifi()

        return mWifiManager.setWifiEnabled(true);
    
protected longgetLastConnectivityChangeTime()

        return mLastConnectivityChangeTime;
    
protected booleanisConnectedToMobile()

        return (mCm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_MOBILE);
    
protected booleanisConnectedToWifi()

        return (mCm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI);
    
protected voidlogv(java.lang.String format, java.lang.Object args)

        Log.v(mLogTag, String.format(format, args));
    
protected booleanpingTest()

return
true if the ping test is successful, false otherwise.

        long startTime = System.currentTimeMillis();
        while ((System.currentTimeMillis() - startTime) < PING_TIMER) {
            try {
                // assume the chance that all servers are down is very small
                for (String host : PING_HOST_LIST) {
                    logv("Start ping test, ping " + host);
                    Process p = Runtime.getRuntime().exec("ping -c 10 -w 100 " + host);
                    int status = p.waitFor();
                    if (status == 0) {
                        // if any of the ping test is successful, return true
                        return true;
                    }
                }
            } catch (UnknownHostException e) {
                logv("Ping test Fail: Unknown Host");
            } catch (IOException e) {
                logv("Ping test Fail:  IOException");
            } catch (InterruptedException e) {
                logv("Ping test Fail: InterruptedException");
            }
            SystemClock.sleep(SHORT_TIMEOUT);
        }
        // ping test timeout
        return false;
    
protected booleanremoveConfiguredNetworksAndDisableWifi()
Remove configured networks and disable wifi

        if (!disconnectAP()) {
           return false;
        }
        SystemClock.sleep(SHORT_TIMEOUT);
        if (!mWifiManager.setWifiEnabled(false)) {
            return false;
        }
        SystemClock.sleep(SHORT_TIMEOUT);
        return true;
    
protected voidsetUp()

        mLastScanResult = null;
        mContext = getInstrumentation().getContext();

        // Get an instance of ConnectivityManager
        mCm = (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        // Get an instance of WifiManager
        mWifiManager =(WifiManager)mContext.getSystemService(Context.WIFI_SERVICE);

        if (mWifiManager.isWifiApEnabled()) {
            // if soft AP is enabled, disable it
            mWifiManager.setWifiApEnabled(null, false);
            logv("Disable soft ap");
        }

        // register a connectivity receiver for CONNECTIVITY_ACTION;
        mConnectivityReceiver = new ConnectivityReceiver();
        mContext.registerReceiver(mConnectivityReceiver,
                new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));

        mWifiReceiver = new WifiReceiver();
        IntentFilter mIntentFilter = new IntentFilter();
        mIntentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
        mIntentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        mIntentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        mIntentFilter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
        mIntentFilter.addAction(WifiManager.WIFI_AP_STATE_CHANGED_ACTION);
        mIntentFilter.addAction(ConnectivityManager.ACTION_TETHER_STATE_CHANGED);
        mContext.registerReceiver(mWifiReceiver, mIntentFilter);

        logv("Clear Wifi before we start the test.");
        removeConfiguredNetworksAndDisableWifi();
     
protected voidtearDown()

        //Unregister receiver
        if (mConnectivityReceiver != null) {
          mContext.unregisterReceiver(mConnectivityReceiver);
        }
        if (mWifiReceiver != null) {
          mContext.unregisterReceiver(mWifiReceiver);
        }
        super.tearDown();
    
protected voidturnScreenOff()

        logv("Turn screen off");
        PowerManager pm =
            (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
        pm.goToSleep(SystemClock.uptimeMillis());
    
protected voidturnScreenOn()

        logv("Turn screen on");
        PowerManager pm =
                (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
        pm.wakeUp(SystemClock.uptimeMillis());
        // disable lock screen
        KeyguardManager km = (KeyguardManager) mContext.getSystemService(Context.KEYGUARD_SERVICE);
        if (km.inKeyguardRestrictedInputMode()) {
            sendKeys(KeyEvent.KEYCODE_MENU);
        }
    
protected booleanwaitForActiveNetworkConnection(long timeout)

        long startTime = SystemClock.uptimeMillis();
        while (true) {
            NetworkInfo ni = mCm.getActiveNetworkInfo();
            if (ni != null && ni.isConnected()) {
                return true;
            }
            if ((SystemClock.uptimeMillis() - startTime) > timeout) {
                logv("waitForActiveNetworkConnection timeout: %s", ni);
                return false;
            }
            logv("waitForActiveNetworkConnection interim: %s", ni);
            SystemClock.sleep(SHORT_TIMEOUT);
        }
    
protected booleanwaitForNetworkState(int networkType, android.net.NetworkInfo.State expectedState, long timeout)

        long startTime = SystemClock.uptimeMillis();
        while (true) {
            NetworkInfo ni = mCm.getNetworkInfo(networkType);
            if (ni != null && expectedState.equals(ni.getState())) {
                logv("waitForNetworkState success: %s", ni);
                return true;
            }
            if ((SystemClock.uptimeMillis() - startTime) > timeout) {
                logv("waitForNetworkState timeout: %s", ni);
                return false;
            }
            logv("waitForNetworkState interim: %s", ni);
            SystemClock.sleep(SHORT_TIMEOUT);
        }
    
protected booleanwaitForTetherStateChange(long timeout)
Wait for the wifi tethering result:

param
timeout is the maximum waiting time
return
SUCCESS if tethering result is successful FAILURE if tethering result returns error.

        long startTime = SystemClock.uptimeMillis();
        String[] wifiRegexes = mCm.getTetherableWifiRegexs();
        while (true) {
            if ((SystemClock.uptimeMillis() - startTime) > timeout) {
                return false;
            }
            String[] active = mCm.getTetheredIfaces();
            String[] error = mCm.getTetheringErroredIfaces();
            for (String iface: active) {
                for (String regex: wifiRegexes) {
                    if (iface.matches(regex)) {
                        return true;
                    }
                }
            }
            for (String iface: error) {
                for (String regex: wifiRegexes) {
                    if (iface.matches(regex)) {
                        return false;
                    }
                }
            }
            SystemClock.sleep(SHORT_TIMEOUT);
        }
    
protected booleanwaitForWifiApState(int expectedState, long timeout)

        long startTime = SystemClock.uptimeMillis();
        while (true) {
            int state = mWifiManager.getWifiApState();
            if (state == expectedState) {
                logv("waitForWifiAPState success: state=" + state);
                return true;
            }
            if ((SystemClock.uptimeMillis() - startTime) > timeout) {
                logv(String.format("waitForWifiAPState timeout: expected=%d, actual=%d",
                        expectedState, state));
                return false;
            }
            logv(String.format("waitForWifiAPState interim: expected=%d, actual=%d",
                    expectedState, state));
            SystemClock.sleep(SHORT_TIMEOUT);
        }
    
protected booleanwaitForWifiState(int expectedState, long timeout)

        long startTime = SystemClock.uptimeMillis();
        while (true) {
            int state = mWifiManager.getWifiState();
            if (state == expectedState) {
                logv("waitForWifiState success: state=" + state);
                return true;
            }
            if ((SystemClock.uptimeMillis() - startTime) > timeout) {
                logv("waitForWifiState timeout: expected=%d, actual=%d", expectedState, state);
                return false;
            }
            logv("waitForWifiState interim: expected=%d, actual=%d", expectedState, state);
            SystemClock.sleep(SHORT_TIMEOUT);
        }
    
protected booleanwaitUntilNoActiveNetworkConnection(long timeout)

        long startTime = SystemClock.uptimeMillis();
        while (true) {
            NetworkInfo ni = mCm.getActiveNetworkInfo();
            if (ni == null) {
                return true;
            }
            if ((SystemClock.uptimeMillis() - startTime) > timeout) {
                logv("waitForActiveNetworkConnection timeout: %s", ni);
                return false;
            }
            logv("waitForActiveNetworkConnection interim: %s", ni);
            SystemClock.sleep(SHORT_TIMEOUT);
        }