Methods Summary |
---|
public void | cleanUp()
// 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 boolean | connectToWifi(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 boolean | connectToWifiWithConfiguration(android.net.wifi.WifiConfiguration config)Connect to Wi-Fi with the given configuration.
// 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.String | convertToQuotedString(java.lang.String string)Add quotes around the string.
return "\"" + string + "\"";
|
public boolean | disableWifi()Disable Wifi
return mWifiManager.setWifiEnabled(false);
|
public boolean | disconnectAP()
// 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 int | downloadManagerUid()Fetch 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 boolean | downloadSuccessful(long enqueue)Determines if a given download was successful by querying the DownloadManager.
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 boolean | enableWifi()Enable Wifi
return mWifiManager.setWifiEnabled(true);
|
public java.lang.String | getTransitionFailureReason(int networkType)Fetch the failure reason for the transition.
Log.v(LOG_TAG, "get network state transition failure reason for " + networkType + ": " +
mConnectivityState[networkType].toString());
return mConnectivityState[networkType].getFailureReason();
|
public boolean | hasData()Helper method used to test data connectivity by pinging a series of popular sites.
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 void | initialize()Initialize the class. Needs to be called before any other methods in {@link ConnectionUtil}
// 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 void | initializeNetworkStates()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 boolean | isConnectedToMobile()Convenience method to determine if we are connected to a mobile network.
NetworkInfo networkInfo = mCM.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
return networkInfo.isConnected();
|
public boolean | isConnectedToWifi()Convenience method to determine if we are connected to wifi.
NetworkInfo networkInfo = mCM.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
return networkInfo.isConnected();
|
private void | notifiyDownloadState()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 void | notifyNetworkConnectivityChange()Send a notification via the mConnectivityMonitor when the network connectivity changes.
synchronized(mConnectivityMonitor) {
Log.v(LOG_TAG, "notify network connectivity changed");
mConnectivityMonitor.notifyAll();
}
|
private void | notifyScanResult()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 void | notifyWifiAPState()Send a notification when the wifi ap state changes.
synchronized (this) {
Log.v(LOG_TAG, "notify wifi AP state changed.");
this.notify();
}
|
private void | notifyWifiState()Send a notification via the mWifiMonitor when the wifi state changes.
synchronized (mWifiMonitor) {
Log.v(LOG_TAG, "notify wifi state changed.");
mWifiMonitor.notify();
}
|
public void | recordNetworkState(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 boolean | removeConfiguredNetworksAndDisableWifi()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 void | setAirplaneMode(android.content.Context context, boolean enableAM)Set airplane mode on device, caller is responsible to ensuring correct state.
//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 void | setStateTransitionCriteria(int networkType, android.net.NetworkInfo.State initState, com.android.bandwidthtest.NetworkState.StateTransitionDirection transitionDir, android.net.NetworkInfo.State targetState)Set the state transition criteria
mConnectivityState[networkType].setStateTransitionCriteria(
initState, transitionDir, targetState);
|
private void | sleep(long sleeptime)Make the current thread sleep.
try {
Thread.sleep(sleeptime);
} catch (InterruptedException e) {}
|
public boolean | startDownloadAndWait(java.lang.String targetUrl, long timeout)Start a download on a given url and wait for completion.
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 boolean | validateNetworkStates(int networkType)Validate the states recorded.
Log.v(LOG_TAG, "validate network state for " + networkType + ": ");
return mConnectivityState[networkType].validateStateTransition();
|
public boolean | waitForNetworkState(int networkType, android.net.NetworkInfo.State expectedState, long timeout)Wait for network connectivity state.
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 boolean | waitForWifiState(int expectedState, long timeout)Wait for a given wifi state to occur within a given timeout.
// 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 void | wifiTestInit()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();
|