ConnectionUtil.java revision 4fe25f693ad311556fb232c352ed0b84d59343a5
1/* 2 * Copyright (C) 2011, The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.bandwidthtest.util; 18 19import android.app.DownloadManager; 20import android.app.DownloadManager.Query; 21import android.app.DownloadManager.Request; 22import android.content.BroadcastReceiver; 23import android.content.Context; 24import android.content.Intent; 25import android.content.IntentFilter; 26import android.content.pm.ApplicationInfo; 27import android.content.pm.PackageManager; 28import android.content.pm.PackageManager.NameNotFoundException; 29import android.database.Cursor; 30import android.net.ConnectivityManager; 31import android.net.NetworkInfo; 32import android.net.NetworkInfo.State; 33import android.net.Uri; 34import android.net.wifi.ScanResult; 35import android.net.wifi.WifiConfiguration; 36import android.net.wifi.WifiConfiguration.KeyMgmt; 37import android.net.wifi.WifiManager; 38import android.os.Handler; 39import android.os.Message; 40import android.provider.Settings; 41import android.util.Log; 42 43import com.android.bandwidthtest.NetworkState; 44import com.android.bandwidthtest.NetworkState.StateTransitionDirection; 45import com.android.internal.util.AsyncChannel; 46 47import junit.framework.Assert; 48 49import java.io.IOException; 50import java.net.UnknownHostException; 51import java.util.List; 52 53/* 54 * Utility class used to set the connectivity of the device and to download files. 55 */ 56public class ConnectionUtil { 57 private static final String LOG_TAG = "ConnectionUtil"; 58 private static final String DOWNLOAD_MANAGER_PKG_NAME = "com.android.providers.downloads"; 59 private static final int WAIT_FOR_SCAN_RESULT = 10 * 1000; // 10 seconds 60 private static final int WIFI_SCAN_TIMEOUT = 50 * 1000; 61 public static final int SHORT_TIMEOUT = 5 * 1000; 62 public static final int LONG_TIMEOUT = 120 * 1000; // 2 minutes 63 private ConnectivityReceiver mConnectivityReceiver = null; 64 private WifiReceiver mWifiReceiver = null; 65 private DownloadReceiver mDownloadReceiver = null; 66 private DownloadManager mDownloadManager; 67 private NetworkInfo mNetworkInfo; 68 private NetworkInfo mOtherNetworkInfo; 69 private boolean mScanResultIsAvailable = false; 70 private ConnectivityManager mCM; 71 private Object mWifiMonitor = new Object(); 72 private Object mConnectivityMonitor = new Object(); 73 private Object mDownloadMonitor = new Object(); 74 private int mWifiState; 75 private NetworkInfo mWifiNetworkInfo; 76 private WifiManager mWifiManager; 77 private Context mContext; 78 // Verify connectivity state 79 private static final int NUM_NETWORK_TYPES = ConnectivityManager.MAX_NETWORK_TYPE + 1; 80 private NetworkState[] mConnectivityState = new NetworkState[NUM_NETWORK_TYPES]; 81 82 public ConnectionUtil(Context context) { 83 mContext = context; 84 } 85 86 /** 87 * Initialize the class. Needs to be called before any other methods in {@link ConnectionUtil} 88 * 89 * @throws Exception 90 */ 91 public void initialize() throws Exception { 92 // Register a connectivity receiver for CONNECTIVITY_ACTION 93 mConnectivityReceiver = new ConnectivityReceiver(); 94 mContext.registerReceiver(mConnectivityReceiver, 95 new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); 96 97 // Register a download receiver for ACTION_DOWNLOAD_COMPLETE 98 mDownloadReceiver = new DownloadReceiver(); 99 mContext.registerReceiver(mDownloadReceiver, 100 new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)); 101 102 // Register a wifi receiver 103 mWifiReceiver = new WifiReceiver(); 104 IntentFilter mIntentFilter = new IntentFilter(); 105 mIntentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION); 106 mIntentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION); 107 mIntentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION); 108 mIntentFilter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION); 109 mIntentFilter.addAction(WifiManager.WIFI_AP_STATE_CHANGED_ACTION); 110 mContext.registerReceiver(mWifiReceiver, mIntentFilter); 111 112 // Get an instance of ConnectivityManager 113 mCM = (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE); 114 115 // Get an instance of WifiManager 116 mWifiManager =(WifiManager)mContext.getSystemService(Context.WIFI_SERVICE); 117 mWifiManager.asyncConnect(mContext, new WifiServiceHandler()); 118 119 mDownloadManager = (DownloadManager)mContext.getSystemService(Context.DOWNLOAD_SERVICE); 120 121 initializeNetworkStates(); 122 123 124 } 125 126 /** 127 * Additional initialization needed for wifi related tests. 128 */ 129 public void wifiTestInit() { 130 mWifiManager.setWifiEnabled(true); 131 Log.v(LOG_TAG, "Clear Wifi before we start the test."); 132 sleep(SHORT_TIMEOUT); 133 removeConfiguredNetworksAndDisableWifi(); 134 } 135 136 137 /** 138 * A wrapper of a broadcast receiver which provides network connectivity information 139 * for all kinds of network: wifi, mobile, etc. 140 */ 141 private class ConnectivityReceiver extends BroadcastReceiver { 142 /** 143 * {@inheritDoc} 144 */ 145 @Override 146 public void onReceive(Context context, Intent intent) { 147 if (isInitialStickyBroadcast()) { 148 Log.d(LOG_TAG, "This is a sticky broadcast don't do anything."); 149 return; 150 } 151 Log.v(LOG_TAG, "ConnectivityReceiver: onReceive() is called with " + intent); 152 String action = intent.getAction(); 153 if (!action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) { 154 Log.v("ConnectivityReceiver", "onReceive() called with " + intent); 155 return; 156 } 157 158 final ConnectivityManager connManager = (ConnectivityManager) context 159 .getSystemService(Context.CONNECTIVITY_SERVICE); 160 mNetworkInfo = connManager.getActiveNetworkInfo(); 161 162 if (intent.hasExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO)) { 163 mOtherNetworkInfo = (NetworkInfo) 164 intent.getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO); 165 } 166 167 Log.v(LOG_TAG, "mNetworkInfo: " + mNetworkInfo.toString()); 168 recordNetworkState(mNetworkInfo.getType(), mNetworkInfo.getState()); 169 if (mOtherNetworkInfo != null) { 170 Log.v(LOG_TAG, "mOtherNetworkInfo: " + mOtherNetworkInfo.toString()); 171 recordNetworkState(mOtherNetworkInfo.getType(), mOtherNetworkInfo.getState()); 172 } 173 notifyNetworkConnectivityChange(); 174 } 175 } 176 177 /** 178 * A wrapper of a broadcast receiver which provides wifi information. 179 */ 180 private class WifiReceiver extends BroadcastReceiver { 181 /** 182 * {@inheritDoc} 183 */ 184 @Override 185 public void onReceive(Context context, Intent intent) { 186 String action = intent.getAction(); 187 Log.v("WifiReceiver", "onReceive() is calleld with " + intent); 188 if (action.equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) { 189 Log.v(LOG_TAG, "Scan results are available"); 190 notifyScanResult(); 191 } else if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) { 192 mWifiNetworkInfo = 193 (NetworkInfo) intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO); 194 Log.v(LOG_TAG, "mWifiNetworkInfo: " + mWifiNetworkInfo.toString()); 195 if (mWifiNetworkInfo.getState() == State.CONNECTED) { 196 intent.getStringExtra(WifiManager.EXTRA_BSSID); 197 } 198 notifyWifiState(); 199 } else if (action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) { 200 mWifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 201 WifiManager.WIFI_STATE_UNKNOWN); 202 notifyWifiState(); 203 } else if (action.equals(WifiManager.WIFI_AP_STATE_CHANGED_ACTION)) { 204 notifyWifiAPState(); 205 } else { 206 return; 207 } 208 } 209 } 210 211 /** 212 * A wrapper of a broadcast receiver which provides download manager information. 213 */ 214 private class DownloadReceiver extends BroadcastReceiver { 215 /** 216 * {@inheritDoc} 217 */ 218 @Override 219 public void onReceive(Context context, Intent intent) { 220 String action = intent.getAction(); 221 Log.v("DownloadReceiver", "onReceive() is called with " + intent); 222 // Download complete 223 if (action.equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) { 224 notifiyDownloadState(); 225 } 226 } 227 } 228 229 private class WifiServiceHandler extends Handler { 230 /** 231 * {@inheritDoc} 232 */ 233 @Override 234 public void handleMessage(Message msg) { 235 switch (msg.what) { 236 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: 237 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) { 238 // AsyncChannel in msg.obj 239 } else { 240 Log.v(LOG_TAG, "Failed to establish AsyncChannel connection"); 241 } 242 break; 243 default: 244 // Ignore 245 break; 246 } 247 } 248 } 249 250 /** 251 * Initialize all the network states. 252 */ 253 public void initializeNetworkStates() { 254 // For each network type, initialize network states to UNKNOWN, and no verification 255 // flag is set. 256 for (int networkType = NUM_NETWORK_TYPES - 1; networkType >= 0; networkType--) { 257 mConnectivityState[networkType] = new NetworkState(); 258 Log.v(LOG_TAG, "Initialize network state for " + networkType + ": " + 259 mConnectivityState[networkType].toString()); 260 } 261 } 262 263 public void recordNetworkState(int networkType, State networkState) { 264 // deposit a network state 265 Log.v(LOG_TAG, "record network state for network " + networkType + 266 ", state is " + networkState); 267 mConnectivityState[networkType].recordState(networkState); 268 } 269 270 /** 271 * Set the state transition criteria 272 * 273 * @param networkType 274 * @param initState 275 * @param transitionDir 276 * @param targetState 277 */ 278 public void setStateTransitionCriteria(int networkType, State initState, 279 StateTransitionDirection transitionDir, State targetState) { 280 mConnectivityState[networkType].setStateTransitionCriteria( 281 initState, transitionDir, targetState); 282 } 283 284 /** 285 * Validate the states recorded. 286 * @param networkType 287 * @return 288 */ 289 public boolean validateNetworkStates(int networkType) { 290 Log.v(LOG_TAG, "validate network state for " + networkType + ": "); 291 return mConnectivityState[networkType].validateStateTransition(); 292 } 293 294 /** 295 * Fetch the failure reason for the transition. 296 * @param networkType 297 * @return result from network state validation 298 */ 299 public String getTransitionFailureReason(int networkType) { 300 Log.v(LOG_TAG, "get network state transition failure reason for " + networkType + ": " + 301 mConnectivityState[networkType].toString()); 302 return mConnectivityState[networkType].getFailureReason(); 303 } 304 305 /** 306 * Send a notification via the mConnectivityMonitor when the network connectivity changes. 307 */ 308 private void notifyNetworkConnectivityChange() { 309 synchronized(mConnectivityMonitor) { 310 Log.v(LOG_TAG, "notify network connectivity changed"); 311 mConnectivityMonitor.notifyAll(); 312 } 313 } 314 315 /** 316 * Send a notification when a scan for the wifi network is done. 317 */ 318 private void notifyScanResult() { 319 synchronized (this) { 320 Log.v(LOG_TAG, "notify that scan results are available"); 321 this.notify(); 322 } 323 } 324 325 /** 326 * Send a notification via the mWifiMonitor when the wifi state changes. 327 */ 328 private void notifyWifiState() { 329 synchronized (mWifiMonitor) { 330 Log.v(LOG_TAG, "notify wifi state changed."); 331 mWifiMonitor.notify(); 332 } 333 } 334 335 /** 336 * Send a notification via the mDownloadMonitor when a download is complete. 337 */ 338 private void notifiyDownloadState() { 339 synchronized (mDownloadMonitor) { 340 Log.v(LOG_TAG, "notifiy download manager state changed."); 341 mDownloadMonitor.notify(); 342 } 343 } 344 345 /** 346 * Send a notification when the wifi ap state changes. 347 */ 348 private void notifyWifiAPState() { 349 synchronized (this) { 350 Log.v(LOG_TAG, "notify wifi AP state changed."); 351 this.notify(); 352 } 353 } 354 355 /** 356 * Start a download on a given url and wait for completion. 357 * 358 * @param targetUrl the target to download.x 359 * @param timeout to wait for download to finish 360 * @return true if we successfully downloaded the requestedUrl, false otherwise. 361 */ 362 public boolean startDownloadAndWait(String targetUrl, long timeout) { 363 if (targetUrl.length() == 0 || targetUrl == null) { 364 Log.v(LOG_TAG, "Empty or Null target url requested to DownloadManager"); 365 return true; 366 } 367 Request request = new Request(Uri.parse(targetUrl)); 368 long enqueue = mDownloadManager.enqueue(request); 369 Log.v(LOG_TAG, "Sending download request of " + targetUrl + " to DownloadManager"); 370 long startTime = System.currentTimeMillis(); 371 while (true) { 372 if ((System.currentTimeMillis() - startTime) > timeout) { 373 Log.v(LOG_TAG, "startDownloadAndWait timed out, failed to fetch " + targetUrl + 374 " within " + timeout); 375 return downloadSuccessful(enqueue); 376 } 377 Log.v(LOG_TAG, "Waiting for the download to finish " + targetUrl); 378 synchronized (mDownloadMonitor) { 379 try { 380 mDownloadMonitor.wait(SHORT_TIMEOUT); 381 } catch (InterruptedException e) { 382 e.printStackTrace(); 383 } 384 if (!downloadSuccessful(enqueue)) { 385 continue; 386 } 387 return true; 388 } 389 } 390 } 391 392 /** 393 * Fetch the Download Manager's UID. 394 * @return the Download Manager's UID 395 */ 396 public int downloadManagerUid() { 397 try { 398 PackageManager pm = mContext.getPackageManager(); 399 ApplicationInfo appInfo = pm.getApplicationInfo(DOWNLOAD_MANAGER_PKG_NAME, 400 PackageManager.GET_META_DATA); 401 return appInfo.uid; 402 } catch (NameNotFoundException e) { 403 Log.d(LOG_TAG, "Did not find the package for the download service."); 404 return -1; 405 } 406 } 407 408 /** 409 * Determines if a given download was successful by querying the DownloadManager. 410 * 411 * @param enqueue the id used to identify/query the DownloadManager with. 412 * @return true if download was successful, false otherwise. 413 */ 414 private boolean downloadSuccessful(long enqueue) { 415 Query query = new Query(); 416 query.setFilterById(enqueue); 417 Cursor c = mDownloadManager.query(query); 418 if (c.moveToFirst()) { 419 int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS); 420 if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) { 421 Log.v(LOG_TAG, "Successfully downloaded file!"); 422 return true; 423 } 424 } 425 return false; 426 } 427 428 /** 429 * Wait for network connectivity state. 430 * @param networkType the network to check for 431 * @param expectedState the desired state 432 * @param timeout in milliseconds 433 * @return true if the network connectivity state matched what was expected 434 */ 435 public boolean waitForNetworkState(int networkType, State expectedState, long timeout) { 436 long startTime = System.currentTimeMillis(); 437 while (true) { 438 if ((System.currentTimeMillis() - startTime) > timeout) { 439 Log.v(LOG_TAG, "waitForNetworkState time out, the state of network type " + networkType + 440 " is: " + mCM.getNetworkInfo(networkType).getState()); 441 if (mCM.getNetworkInfo(networkType).getState() != expectedState) { 442 return false; 443 } else { 444 // the broadcast has been sent out. the state has been changed. 445 Log.v(LOG_TAG, "networktype: " + networkType + " state: " + 446 mCM.getNetworkInfo(networkType)); 447 return true; 448 } 449 } 450 Log.v(LOG_TAG, "Wait for the connectivity state for network: " + networkType + 451 " to be " + expectedState.toString()); 452 synchronized (mConnectivityMonitor) { 453 try { 454 mConnectivityMonitor.wait(SHORT_TIMEOUT); 455 } catch (InterruptedException e) { 456 e.printStackTrace(); 457 } 458 if (mNetworkInfo == null) { 459 Log.v(LOG_TAG, "Do not have networkInfo! Force fetch of network info."); 460 mNetworkInfo = mCM.getActiveNetworkInfo(); 461 Assert.assertNotNull(mNetworkInfo); 462 } 463 if ((mNetworkInfo.getType() != networkType) || 464 (mNetworkInfo.getState() != expectedState)) { 465 Log.v(LOG_TAG, "network state for " + mNetworkInfo.getType() + 466 "is: " + mNetworkInfo.getState()); 467 continue; 468 } 469 return true; 470 } 471 } 472 } 473 474 /** 475 * Wait for a given wifi state to occur within a given timeout. 476 * @param expectedState the expected wifi state. 477 * @param timeout for the state to be set in milliseconds. 478 * @return true if the state was achieved within the timeout, false otherwise. 479 */ 480 public boolean waitForWifiState(int expectedState, long timeout) { 481 // Wait for Wifi state: WIFI_STATE_DISABLED, WIFI_STATE_DISABLING, WIFI_STATE_ENABLED, 482 // WIFI_STATE_ENALBING, WIFI_STATE_UNKNOWN 483 long startTime = System.currentTimeMillis(); 484 while (true) { 485 if ((System.currentTimeMillis() - startTime) > timeout) { 486 if (mWifiState != expectedState) { 487 return false; 488 } else { 489 return true; 490 } 491 } 492 Log.v(LOG_TAG, "Wait for wifi state to be: " + expectedState); 493 synchronized (mWifiMonitor) { 494 try { 495 mWifiMonitor.wait(SHORT_TIMEOUT); 496 } catch (InterruptedException e) { 497 e.printStackTrace(); 498 } 499 if (mWifiState != expectedState) { 500 Log.v(LOG_TAG, "Wifi state is: " + mWifiState); 501 continue; 502 } 503 return true; 504 } 505 } 506 } 507 508 /** 509 * Convenience method to determine if we are connected to a mobile network. 510 * @return true if connected to a mobile network, false otherwise. 511 */ 512 public boolean isConnectedToMobile() { 513 NetworkInfo networkInfo = mCM.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); 514 return networkInfo.isConnected(); 515 } 516 517 /** 518 * Convenience method to determine if we are connected to wifi. 519 * @return true if connected to wifi, false otherwise. 520 */ 521 public boolean isConnectedToWifi() { 522 NetworkInfo networkInfo = mCM.getNetworkInfo(ConnectivityManager.TYPE_WIFI); 523 return networkInfo.isConnected(); 524 } 525 526 /** 527 * Associate the device to given SSID 528 * If the device is already associated with a WiFi, disconnect and forget it, 529 * We don't verify whether the connection is successful or not, leave this to the test 530 */ 531 public boolean connectToWifi(String knownSSID) { 532 WifiConfiguration config = new WifiConfiguration(); 533 config.SSID = knownSSID; 534 config.allowedKeyManagement.set(KeyMgmt.NONE); 535 return connectToWifiWithConfiguration(config); 536 } 537 538 /** 539 * Connect to Wi-Fi with the given configuration. 540 * @param config 541 * @return true if we are connected to a given AP. 542 */ 543 public boolean connectToWifiWithConfiguration(WifiConfiguration config) { 544 // The SSID in the configuration is a pure string, need to convert it to a quoted string. 545 String ssid = config.SSID; 546 config.SSID = convertToQuotedString(ssid); 547 548 // If wifi is not enabled, enable it 549 if (!mWifiManager.isWifiEnabled()) { 550 Log.v(LOG_TAG, "Wifi is not enabled, enable it"); 551 mWifiManager.setWifiEnabled(true); 552 // wait for the wifi state change before start scanning. 553 if (!waitForWifiState(WifiManager.WIFI_STATE_ENABLED, 2 * SHORT_TIMEOUT)) { 554 Log.v(LOG_TAG, "Wait for WIFI_STATE_ENABLED failed"); 555 return false; 556 } 557 } 558 559 boolean foundApInScanResults = false; 560 for (int retry = 0; retry < 5; retry++) { 561 List<ScanResult> netList = mWifiManager.getScanResults(); 562 if (netList != null) { 563 Log.v(LOG_TAG, "size of scan result list: " + netList.size()); 564 for (int i = 0; i < netList.size(); i++) { 565 ScanResult sr= netList.get(i); 566 if (sr.SSID.equals(ssid)) { 567 Log.v(LOG_TAG, "Found " + ssid + " in the scan result list."); 568 Log.v(LOG_TAG, "Retry: " + retry); 569 foundApInScanResults = true; 570 mWifiManager.connectNetwork(config); 571 break; 572 } 573 } 574 } 575 if (foundApInScanResults) { 576 return true; 577 } else { 578 // Start an active scan 579 mWifiManager.startScanActive(); 580 mScanResultIsAvailable = false; 581 long startTime = System.currentTimeMillis(); 582 while (!mScanResultIsAvailable) { 583 if ((System.currentTimeMillis() - startTime) > WIFI_SCAN_TIMEOUT) { 584 Log.v(LOG_TAG, "wait for scan results timeout"); 585 return false; 586 } 587 // wait for the scan results to be available 588 synchronized (this) { 589 // wait for the scan result to be available 590 try { 591 this.wait(WAIT_FOR_SCAN_RESULT); 592 } catch (InterruptedException e) { 593 e.printStackTrace(); 594 } 595 if ((mWifiManager.getScanResults() == null) || 596 (mWifiManager.getScanResults().size() <= 0)) { 597 continue; 598 } 599 mScanResultIsAvailable = true; 600 } 601 } 602 } 603 } 604 return false; 605 } 606 607 /* 608 * Disconnect from the current AP and remove configured networks. 609 */ 610 public boolean disconnectAP() { 611 // remove saved networks 612 List<WifiConfiguration> wifiConfigList = mWifiManager.getConfiguredNetworks(); 613 Log.v(LOG_TAG, "size of wifiConfigList: " + wifiConfigList.size()); 614 for (WifiConfiguration wifiConfig: wifiConfigList) { 615 Log.v(LOG_TAG, "Remove wifi configuration: " + wifiConfig.networkId); 616 int netId = wifiConfig.networkId; 617 mWifiManager.forgetNetwork(netId); 618 } 619 return true; 620 } 621 622 /** 623 * Enable Wifi 624 * @return true if Wifi is enabled successfully 625 */ 626 public boolean enableWifi() { 627 return mWifiManager.setWifiEnabled(true); 628 } 629 630 /** 631 * Disable Wifi 632 * @return true if Wifi is disabled successfully 633 */ 634 public boolean disableWifi() { 635 return mWifiManager.setWifiEnabled(false); 636 } 637 638 /** 639 * Remove configured networks and disable wifi 640 */ 641 public boolean removeConfiguredNetworksAndDisableWifi() { 642 if (!disconnectAP()) { 643 return false; 644 } 645 sleep(SHORT_TIMEOUT); 646 if (!mWifiManager.setWifiEnabled(false)) { 647 return false; 648 } 649 sleep(SHORT_TIMEOUT); 650 return true; 651 } 652 653 /** 654 * Make the current thread sleep. 655 * @param sleeptime the time to sleep in milliseconds 656 */ 657 private void sleep(long sleeptime) { 658 try { 659 Thread.sleep(sleeptime); 660 } catch (InterruptedException e) {} 661 } 662 663 /** 664 * Set airplane mode on device, caller is responsible to ensuring correct state. 665 * @param context {@link Context} 666 * @param enableAM to enable or disable airplane mode. 667 */ 668 public void setAirplaneMode(Context context, boolean enableAM) { 669 //set the airplane mode 670 Settings.System.putInt(context.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 671 enableAM ? 1 : 0); 672 // Post the intent 673 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED); 674 intent.putExtra("state", enableAM); 675 context.sendBroadcast(intent); 676 } 677 678 /** 679 * Add quotes around the string. 680 * @param string to convert 681 * @return string with quotes around it 682 */ 683 protected static String convertToQuotedString(String string) { 684 return "\"" + string + "\""; 685 } 686 687 public void cleanUp() { 688 // Unregister receivers if defined. 689 if (mConnectivityReceiver != null) { 690 mContext.unregisterReceiver(mConnectivityReceiver); 691 } 692 if (mWifiReceiver != null) { 693 mContext.unregisterReceiver(mWifiReceiver); 694 } 695 if (mDownloadReceiver != null) { 696 mContext.unregisterReceiver(mDownloadReceiver); 697 } 698 Log.v(LOG_TAG, "onDestroy, inst=" + Integer.toHexString(hashCode())); 699 } 700 701 /** 702 * Helper method used to test data connectivity by pinging a series of popular sites. 703 * @return true if device has data connectivity, false otherwise. 704 */ 705 public boolean hasData() { 706 String[] hostList = {"www.google.com", "www.yahoo.com", 707 "www.bing.com", "www.facebook.com", "www.ask.com"}; 708 try { 709 for (int i = 0; i < hostList.length; ++i) { 710 String host = hostList[i]; 711 Process p = Runtime.getRuntime().exec("ping -c 10 -w 100 " + host); 712 int status = p.waitFor(); 713 if (status == 0) { 714 return true; 715 } 716 } 717 } catch (UnknownHostException e) { 718 Log.e(LOG_TAG, "Ping test Failed: Unknown Host"); 719 } catch (IOException e) { 720 Log.e(LOG_TAG, "Ping test Failed: IOException"); 721 } catch (InterruptedException e) { 722 Log.e(LOG_TAG, "Ping test Failed: InterruptedException"); 723 } 724 return false; 725 } 726}