FileDocCategorySizeDatePackage
ConnectionUtil.javaAPI DocAndroid 5.1 API28829Thu Mar 12 22:22:12 GMT 2015com.android.bandwidthtest.util

ConnectionUtil

public class ConnectionUtil extends Object

Fields Summary
private static final String
LOG_TAG
private static final String
DOWNLOAD_MANAGER_PKG_NAME
private static final int
WAIT_FOR_SCAN_RESULT
private static final int
WIFI_SCAN_TIMEOUT
public static final int
SHORT_TIMEOUT
public static final int
LONG_TIMEOUT
private ConnectivityReceiver
mConnectivityReceiver
private WifiReceiver
mWifiReceiver
private DownloadReceiver
mDownloadReceiver
private android.app.DownloadManager
mDownloadManager
private android.net.NetworkInfo
mNetworkInfo
private android.net.NetworkInfo
mOtherNetworkInfo
private boolean
mScanResultIsAvailable
private android.net.ConnectivityManager
mCM
private Object
mWifiMonitor
private Object
mConnectivityMonitor
private Object
mDownloadMonitor
private int
mWifiState
private android.net.NetworkInfo
mWifiNetworkInfo
private android.net.wifi.WifiManager
mWifiManager
private android.content.Context
mContext
private static final int
NUM_NETWORK_TYPES
private com.android.bandwidthtest.NetworkState[]
mConnectivityState
Constructors Summary
public ConnectionUtil(android.content.Context context)


       
        mContext = context;
    
Methods Summary
public voidcleanUp()

        // Unregister receivers if defined.
        if (mConnectivityReceiver != null) {
            mContext.unregisterReceiver(mConnectivityReceiver);
        }
        if (mWifiReceiver != null) {
            mContext.unregisterReceiver(mWifiReceiver);
        }
        if (mDownloadReceiver != null) {
            mContext.unregisterReceiver(mDownloadReceiver);
        }
        Log.v(LOG_TAG, "onDestroy, inst=" + Integer.toHexString(hashCode()));
    
public booleanconnectToWifi(java.lang.String knownSSID)
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 = new WifiConfiguration();
        config.SSID = knownSSID;
        config.allowedKeyManagement.set(KeyMgmt.NONE);
        return connectToWifiWithConfiguration(config);
    
public booleanconnectToWifiWithConfiguration(android.net.wifi.WifiConfiguration config)
Connect to Wi-Fi with the given configuration.

param
config
return
true if we are connected to a given AP.

        //  The SSID in the configuration is a pure string, need to convert it to a quoted string.
        String ssid = config.SSID;
        config.SSID = convertToQuotedString(ssid);

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

        boolean foundApInScanResults = false;
        for (int retry = 0; retry < 5; retry++) {
            List<ScanResult> netList = mWifiManager.getScanResults();
            if (netList != null) {
                Log.v(LOG_TAG, "size of scan result list: " + netList.size());
                for (int i = 0; i < netList.size(); i++) {
                    ScanResult sr= netList.get(i);
                    if (sr.SSID.equals(ssid)) {
                        Log.v(LOG_TAG, "Found " + ssid + " in the scan result list.");
                        Log.v(LOG_TAG, "Retry: " + retry);
                        foundApInScanResults = true;
                        mWifiManager.connect(config, new WifiManager.ActionListener() {
                                public void onSuccess() {
                                }
                                public void onFailure(int reason) {
                                    Log.e(LOG_TAG, "connect failed " + reason);
                                }
                            });

                        break;
                    }
                }
            }
            if (foundApInScanResults) {
                return true;
            } else {
                // Start an active scan
                mWifiManager.startScan();
                mScanResultIsAvailable = false;
                long startTime = System.currentTimeMillis();
                while (!mScanResultIsAvailable) {
                    if ((System.currentTimeMillis() - startTime) > WIFI_SCAN_TIMEOUT) {
                        Log.v(LOG_TAG, "wait for scan results timeout");
                        return false;
                    }
                    // wait for the scan results to be available
                    synchronized (this) {
                        // wait for the scan result to be available
                        try {
                            this.wait(WAIT_FOR_SCAN_RESULT);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        if ((mWifiManager.getScanResults() == null) ||
                                (mWifiManager.getScanResults().size() <= 0)) {
                            continue;
                        }
                        mScanResultIsAvailable = true;
                    }
                }
            }
        }
        return false;
    
protected static java.lang.StringconvertToQuotedString(java.lang.String string)
Add quotes around the string.

param
string to convert
return
string with quotes around it

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

return
true if Wifi is disabled successfully

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

        // remove saved networks
        List<WifiConfiguration> wifiConfigList = mWifiManager.getConfiguredNetworks();
        Log.v(LOG_TAG, "size of wifiConfigList: " + wifiConfigList.size());
        for (WifiConfiguration wifiConfig: wifiConfigList) {
            Log.v(LOG_TAG, "Remove wifi configuration: " + wifiConfig.networkId);
            int netId = wifiConfig.networkId;
            mWifiManager.forget(netId, new WifiManager.ActionListener() {
                    public void onSuccess() {
                    }
                    public void onFailure(int reason) {
                        Log.e(LOG_TAG, "forget failed " + reason);
                    }
                });
        }
        return true;
    
public intdownloadManagerUid()
Fetch the Download Manager's UID.

return
the Download Manager's UID

        try {
            PackageManager pm = mContext.getPackageManager();
            ApplicationInfo appInfo = pm.getApplicationInfo(DOWNLOAD_MANAGER_PKG_NAME,
                    PackageManager.GET_META_DATA);
            return appInfo.uid;
        } catch (NameNotFoundException e) {
            Log.d(LOG_TAG, "Did not find the package for the download service.");
            return -1;
        }
    
private booleandownloadSuccessful(long enqueue)
Determines if a given download was successful by querying the DownloadManager.

param
enqueue the id used to identify/query the DownloadManager with.
return
true if download was successful, false otherwise.

        Query query = new Query();
        query.setFilterById(enqueue);
        Cursor c = mDownloadManager.query(query);
        if (c.moveToFirst()) {
            int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
            if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) {
                Log.v(LOG_TAG, "Successfully downloaded file!");
                return true;
            }
        }
        return false;
    
public booleanenableWifi()
Enable Wifi

return
true if Wifi is enabled successfully

        return mWifiManager.setWifiEnabled(true);
    
public java.lang.StringgetTransitionFailureReason(int networkType)
Fetch the failure reason for the transition.

param
networkType
return
result from network state validation

        Log.v(LOG_TAG, "get network state transition failure reason for " + networkType + ": " +
                mConnectivityState[networkType].toString());
        return mConnectivityState[networkType].getFailureReason();
    
public booleanhasData()
Helper method used to test data connectivity by pinging a series of popular sites.

return
true if device has data connectivity, false otherwise.

        String[] hostList = {"www.google.com", "www.yahoo.com",
                "www.bing.com", "www.facebook.com", "www.ask.com"};
        try {
            for (int i = 0; i < hostList.length; ++i) {
                String host = hostList[i];
                Process p = Runtime.getRuntime().exec("ping -c 10 -w 100 " + host);
                int status = p.waitFor();
                if (status == 0) {
                    return true;
                }
            }
        } catch (UnknownHostException e) {
            Log.e(LOG_TAG, "Ping test Failed: Unknown Host");
        } catch (IOException e) {
            Log.e(LOG_TAG, "Ping test Failed: IOException");
        } catch (InterruptedException e) {
            Log.e(LOG_TAG, "Ping test Failed: InterruptedException");
        }
        return false;
    
public voidinitialize()
Initialize the class. Needs to be called before any other methods in {@link ConnectionUtil}

throws
Exception

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

        // Register a download receiver for ACTION_DOWNLOAD_COMPLETE
        mDownloadReceiver = new DownloadReceiver();
        mContext.registerReceiver(mDownloadReceiver,
                new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

        // Register a wifi receiver
        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);
        mContext.registerReceiver(mWifiReceiver, mIntentFilter);

        // Get an instance of ConnectivityManager
        mCM = (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);

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

        mDownloadManager = (DownloadManager)mContext.getSystemService(Context.DOWNLOAD_SERVICE);

        initializeNetworkStates();


    
public voidinitializeNetworkStates()
Initialize all the network states.

        // For each network type, initialize network states to UNKNOWN, and no verification
        // flag is set.
        for (int networkType = NUM_NETWORK_TYPES - 1; networkType >= 0; networkType--) {
            mConnectivityState[networkType] =  new NetworkState();
            Log.v(LOG_TAG, "Initialize network state for " + networkType + ": " +
                    mConnectivityState[networkType].toString());
        }
    
public booleanisConnectedToMobile()
Convenience method to determine if we are connected to a mobile network.

return
true if connected to a mobile network, false otherwise.

        NetworkInfo networkInfo = mCM.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        return networkInfo.isConnected();
    
public booleanisConnectedToWifi()
Convenience method to determine if we are connected to wifi.

return
true if connected to wifi, false otherwise.

        NetworkInfo networkInfo = mCM.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        return networkInfo.isConnected();
    
private voidnotifiyDownloadState()
Send a notification via the mDownloadMonitor when a download is complete.

        synchronized (mDownloadMonitor) {
            Log.v(LOG_TAG, "notifiy download manager state changed.");
            mDownloadMonitor.notify();
        }
    
private voidnotifyNetworkConnectivityChange()
Send a notification via the mConnectivityMonitor when the network connectivity changes.

        synchronized(mConnectivityMonitor) {
            Log.v(LOG_TAG, "notify network connectivity changed");
            mConnectivityMonitor.notifyAll();
        }
    
private voidnotifyScanResult()
Send a notification when a scan for the wifi network is done.

        synchronized (this) {
            Log.v(LOG_TAG, "notify that scan results are available");
            this.notify();
        }
    
private voidnotifyWifiAPState()
Send a notification when the wifi ap state changes.

        synchronized (this) {
            Log.v(LOG_TAG, "notify wifi AP state changed.");
            this.notify();
        }
    
private voidnotifyWifiState()
Send a notification via the mWifiMonitor when the wifi state changes.

        synchronized (mWifiMonitor) {
            Log.v(LOG_TAG, "notify wifi state changed.");
            mWifiMonitor.notify();
        }
    
public voidrecordNetworkState(int networkType, android.net.NetworkInfo.State networkState)

        // deposit a network state
        Log.v(LOG_TAG, "record network state for network " +  networkType +
                ", state is " + networkState);
        mConnectivityState[networkType].recordState(networkState);
    
public booleanremoveConfiguredNetworksAndDisableWifi()
Remove configured networks and disable wifi

        if (!disconnectAP()) {
            return false;
        }
        sleep(SHORT_TIMEOUT);
        if (!mWifiManager.setWifiEnabled(false)) {
            return false;
        }
        sleep(SHORT_TIMEOUT);
        return true;
    
public voidsetAirplaneMode(android.content.Context context, boolean enableAM)
Set airplane mode on device, caller is responsible to ensuring correct state.

param
context {@link Context}
param
enableAM to enable or disable airplane mode.

        //set the airplane mode
        Settings.System.putInt(context.getContentResolver(), Settings.System.AIRPLANE_MODE_ON,
                enableAM ? 1 : 0);
        // Post the intent
        Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
        intent.putExtra("state", enableAM);
        context.sendBroadcast(intent);
    
public voidsetStateTransitionCriteria(int networkType, android.net.NetworkInfo.State initState, com.android.bandwidthtest.NetworkState.StateTransitionDirection transitionDir, android.net.NetworkInfo.State targetState)
Set the state transition criteria

param
networkType
param
initState
param
transitionDir
param
targetState

        mConnectivityState[networkType].setStateTransitionCriteria(
                initState, transitionDir, targetState);
    
private voidsleep(long sleeptime)
Make the current thread sleep.

param
sleeptime the time to sleep in milliseconds

        try {
            Thread.sleep(sleeptime);
        } catch (InterruptedException e) {}
    
public booleanstartDownloadAndWait(java.lang.String targetUrl, long timeout)
Start a download on a given url and wait for completion.

param
targetUrl the target to download.x
param
timeout to wait for download to finish
return
true if we successfully downloaded the requestedUrl, false otherwise.

        if (targetUrl.length() == 0 || targetUrl == null) {
            Log.v(LOG_TAG, "Empty or Null target url requested to DownloadManager");
            return true;
        }
        Request request = new Request(Uri.parse(targetUrl));
        long enqueue = mDownloadManager.enqueue(request);
        Log.v(LOG_TAG, "Sending download request of " + targetUrl + " to DownloadManager");
        long startTime = System.currentTimeMillis();
        while (true) {
            if ((System.currentTimeMillis() - startTime) > timeout) {
                Log.v(LOG_TAG, "startDownloadAndWait timed out, failed to fetch " + targetUrl +
                        " within " + timeout);
                return downloadSuccessful(enqueue);
            }
            Log.v(LOG_TAG, "Waiting for the download to finish " + targetUrl);
            synchronized (mDownloadMonitor) {
                try {
                    mDownloadMonitor.wait(SHORT_TIMEOUT);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (!downloadSuccessful(enqueue)) {
                    continue;
                }
                return true;
            }
        }
    
public booleanvalidateNetworkStates(int networkType)
Validate the states recorded.

param
networkType
return

        Log.v(LOG_TAG, "validate network state for " + networkType + ": ");
        return mConnectivityState[networkType].validateStateTransition();
    
public booleanwaitForNetworkState(int networkType, android.net.NetworkInfo.State expectedState, long timeout)
Wait for network connectivity state.

param
networkType the network to check for
param
expectedState the desired state
param
timeout in milliseconds
return
true if the network connectivity state matched what was expected

        long startTime = System.currentTimeMillis();
        while (true) {
            if ((System.currentTimeMillis() - startTime) > timeout) {
                Log.v(LOG_TAG, "waitForNetworkState time out, the state of network type " + networkType +
                        " is: " + mCM.getNetworkInfo(networkType).getState());
                if (mCM.getNetworkInfo(networkType).getState() != expectedState) {
                    return false;
                } else {
                    // the broadcast has been sent out. the state has been changed.
                    Log.v(LOG_TAG, "networktype: " + networkType + " state: " +
                            mCM.getNetworkInfo(networkType));
                    return true;
                }
            }
            Log.v(LOG_TAG, "Wait for the connectivity state for network: " + networkType +
                    " to be " + expectedState.toString());
            synchronized (mConnectivityMonitor) {
                try {
                    mConnectivityMonitor.wait(SHORT_TIMEOUT);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (mNetworkInfo == null) {
                    Log.v(LOG_TAG, "Do not have networkInfo! Force fetch of network info.");
                    mNetworkInfo = mCM.getActiveNetworkInfo();
                }
                // Still null after force fetch? Maybe the network did not have time to be brought
                // up yet.
                if (mNetworkInfo == null) {
                    Log.v(LOG_TAG, "Failed to force fetch networkInfo. " +
                            "The network is still not ready. Wait for the next broadcast");
                    continue;
                }
                if ((mNetworkInfo.getType() != networkType) ||
                        (mNetworkInfo.getState() != expectedState)) {
                    Log.v(LOG_TAG, "network state for " + mNetworkInfo.getType() +
                            "is: " + mNetworkInfo.getState());
                    continue;
                }
                return true;
            }
        }
    
public booleanwaitForWifiState(int expectedState, long timeout)
Wait for a given wifi state to occur within a given timeout.

param
expectedState the expected wifi state.
param
timeout for the state to be set in milliseconds.
return
true if the state was achieved within the timeout, false otherwise.

        // Wait for Wifi state: WIFI_STATE_DISABLED, WIFI_STATE_DISABLING, WIFI_STATE_ENABLED,
        //                      WIFI_STATE_ENALBING, WIFI_STATE_UNKNOWN
        long startTime = System.currentTimeMillis();
        while (true) {
            if ((System.currentTimeMillis() - startTime) > timeout) {
                if (mWifiState != expectedState) {
                    return false;
                } else {
                    return true;
                }
            }
            Log.v(LOG_TAG, "Wait for wifi state to be: " + expectedState);
            synchronized (mWifiMonitor) {
                try {
                    mWifiMonitor.wait(SHORT_TIMEOUT);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (mWifiState != expectedState) {
                    Log.v(LOG_TAG, "Wifi state is: " + mWifiState);
                    continue;
                }
                return true;
            }
        }
    
public voidwifiTestInit()
Additional initialization needed for wifi related tests.

        mWifiManager.setWifiEnabled(true);
        Log.v(LOG_TAG, "Clear Wifi before we start the test.");
        sleep(SHORT_TIMEOUT);
        removeConfiguredNetworksAndDisableWifi();