WifiManager.java revision f6307820c88e694e102824225b9d8caa6de75a30
1/* 2 * Copyright (C) 2008 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 android.net.wifi; 18 19import android.annotation.SdkConstant; 20import android.annotation.SdkConstant.SdkConstantType; 21import android.content.Context; 22import android.net.DhcpInfo; 23import android.os.Binder; 24import android.os.IBinder; 25import android.os.Handler; 26import android.os.HandlerThread; 27import android.os.Looper; 28import android.os.Message; 29import android.os.RemoteException; 30import android.os.WorkSource; 31import android.os.Messenger; 32import android.util.Log; 33import android.util.SparseArray; 34 35import java.util.concurrent.CountDownLatch; 36 37import com.android.internal.util.AsyncChannel; 38import com.android.internal.util.Protocol; 39 40import java.util.List; 41 42/** 43 * This class provides the primary API for managing all aspects of Wi-Fi 44 * connectivity. Get an instance of this class by calling 45 * {@link android.content.Context#getSystemService(String) Context.getSystemService(Context.WIFI_SERVICE)}. 46 47 * It deals with several categories of items: 48 * <ul> 49 * <li>The list of configured networks. The list can be viewed and updated, 50 * and attributes of individual entries can be modified.</li> 51 * <li>The currently active Wi-Fi network, if any. Connectivity can be 52 * established or torn down, and dynamic information about the state of 53 * the network can be queried.</li> 54 * <li>Results of access point scans, containing enough information to 55 * make decisions about what access point to connect to.</li> 56 * <li>It defines the names of various Intent actions that are broadcast 57 * upon any sort of change in Wi-Fi state. 58 * </ul> 59 * This is the API to use when performing Wi-Fi specific operations. To 60 * perform operations that pertain to network connectivity at an abstract 61 * level, use {@link android.net.ConnectivityManager}. 62 */ 63public class WifiManager { 64 65 private static final String TAG = "WifiManager"; 66 // Supplicant error codes: 67 /** 68 * The error code if there was a problem authenticating. 69 */ 70 public static final int ERROR_AUTHENTICATING = 1; 71 72 /** 73 * Broadcast intent action indicating that Wi-Fi has been enabled, disabled, 74 * enabling, disabling, or unknown. One extra provides this state as an int. 75 * Another extra provides the previous state, if available. 76 * 77 * @see #EXTRA_WIFI_STATE 78 * @see #EXTRA_PREVIOUS_WIFI_STATE 79 */ 80 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) 81 public static final String WIFI_STATE_CHANGED_ACTION = 82 "android.net.wifi.WIFI_STATE_CHANGED"; 83 /** 84 * The lookup key for an int that indicates whether Wi-Fi is enabled, 85 * disabled, enabling, disabling, or unknown. Retrieve it with 86 * {@link android.content.Intent#getIntExtra(String,int)}. 87 * 88 * @see #WIFI_STATE_DISABLED 89 * @see #WIFI_STATE_DISABLING 90 * @see #WIFI_STATE_ENABLED 91 * @see #WIFI_STATE_ENABLING 92 * @see #WIFI_STATE_UNKNOWN 93 */ 94 public static final String EXTRA_WIFI_STATE = "wifi_state"; 95 /** 96 * The previous Wi-Fi state. 97 * 98 * @see #EXTRA_WIFI_STATE 99 */ 100 public static final String EXTRA_PREVIOUS_WIFI_STATE = "previous_wifi_state"; 101 102 /** 103 * Wi-Fi is currently being disabled. The state will change to {@link #WIFI_STATE_DISABLED} if 104 * it finishes successfully. 105 * 106 * @see #WIFI_STATE_CHANGED_ACTION 107 * @see #getWifiState() 108 */ 109 public static final int WIFI_STATE_DISABLING = 0; 110 /** 111 * Wi-Fi is disabled. 112 * 113 * @see #WIFI_STATE_CHANGED_ACTION 114 * @see #getWifiState() 115 */ 116 public static final int WIFI_STATE_DISABLED = 1; 117 /** 118 * Wi-Fi is currently being enabled. The state will change to {@link #WIFI_STATE_ENABLED} if 119 * it finishes successfully. 120 * 121 * @see #WIFI_STATE_CHANGED_ACTION 122 * @see #getWifiState() 123 */ 124 public static final int WIFI_STATE_ENABLING = 2; 125 /** 126 * Wi-Fi is enabled. 127 * 128 * @see #WIFI_STATE_CHANGED_ACTION 129 * @see #getWifiState() 130 */ 131 public static final int WIFI_STATE_ENABLED = 3; 132 /** 133 * Wi-Fi is in an unknown state. This state will occur when an error happens while enabling 134 * or disabling. 135 * 136 * @see #WIFI_STATE_CHANGED_ACTION 137 * @see #getWifiState() 138 */ 139 public static final int WIFI_STATE_UNKNOWN = 4; 140 141 /** 142 * Broadcast intent action indicating that Wi-Fi AP has been enabled, disabled, 143 * enabling, disabling, or failed. 144 * 145 * @hide 146 */ 147 public static final String WIFI_AP_STATE_CHANGED_ACTION = 148 "android.net.wifi.WIFI_AP_STATE_CHANGED"; 149 150 /** 151 * The lookup key for an int that indicates whether Wi-Fi AP is enabled, 152 * disabled, enabling, disabling, or failed. Retrieve it with 153 * {@link android.content.Intent#getIntExtra(String,int)}. 154 * 155 * @see #WIFI_AP_STATE_DISABLED 156 * @see #WIFI_AP_STATE_DISABLING 157 * @see #WIFI_AP_STATE_ENABLED 158 * @see #WIFI_AP_STATE_ENABLING 159 * @see #WIFI_AP_STATE_FAILED 160 * 161 * @hide 162 */ 163 public static final String EXTRA_WIFI_AP_STATE = "wifi_state"; 164 /** 165 * The previous Wi-Fi state. 166 * 167 * @see #EXTRA_WIFI_AP_STATE 168 * 169 * @hide 170 */ 171 public static final String EXTRA_PREVIOUS_WIFI_AP_STATE = "previous_wifi_state"; 172 /** 173 * Wi-Fi AP is currently being disabled. The state will change to 174 * {@link #WIFI_AP_STATE_DISABLED} if it finishes successfully. 175 * 176 * @see #WIFI_AP_STATE_CHANGED_ACTION 177 * @see #getWifiApState() 178 * 179 * @hide 180 */ 181 public static final int WIFI_AP_STATE_DISABLING = 10; 182 /** 183 * Wi-Fi AP is disabled. 184 * 185 * @see #WIFI_AP_STATE_CHANGED_ACTION 186 * @see #getWifiState() 187 * 188 * @hide 189 */ 190 public static final int WIFI_AP_STATE_DISABLED = 11; 191 /** 192 * Wi-Fi AP is currently being enabled. The state will change to 193 * {@link #WIFI_AP_STATE_ENABLED} if it finishes successfully. 194 * 195 * @see #WIFI_AP_STATE_CHANGED_ACTION 196 * @see #getWifiApState() 197 * 198 * @hide 199 */ 200 public static final int WIFI_AP_STATE_ENABLING = 12; 201 /** 202 * Wi-Fi AP is enabled. 203 * 204 * @see #WIFI_AP_STATE_CHANGED_ACTION 205 * @see #getWifiApState() 206 * 207 * @hide 208 */ 209 public static final int WIFI_AP_STATE_ENABLED = 13; 210 /** 211 * Wi-Fi AP is in a failed state. This state will occur when an error occurs during 212 * enabling or disabling 213 * 214 * @see #WIFI_AP_STATE_CHANGED_ACTION 215 * @see #getWifiApState() 216 * 217 * @hide 218 */ 219 public static final int WIFI_AP_STATE_FAILED = 14; 220 221 /** 222 * Broadcast intent action indicating that a connection to the supplicant has 223 * been established (and it is now possible 224 * to perform Wi-Fi operations) or the connection to the supplicant has been 225 * lost. One extra provides the connection state as a boolean, where {@code true} 226 * means CONNECTED. 227 * @see #EXTRA_SUPPLICANT_CONNECTED 228 */ 229 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) 230 public static final String SUPPLICANT_CONNECTION_CHANGE_ACTION = 231 "android.net.wifi.supplicant.CONNECTION_CHANGE"; 232 /** 233 * The lookup key for a boolean that indicates whether a connection to 234 * the supplicant daemon has been gained or lost. {@code true} means 235 * a connection now exists. 236 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}. 237 */ 238 public static final String EXTRA_SUPPLICANT_CONNECTED = "connected"; 239 /** 240 * Broadcast intent action indicating that the state of Wi-Fi connectivity 241 * has changed. One extra provides the new state 242 * in the form of a {@link android.net.NetworkInfo} object. If the new 243 * state is CONNECTED, additional extras may provide the BSSID and WifiInfo of 244 * the access point. 245 * as a {@code String}. 246 * @see #EXTRA_NETWORK_INFO 247 * @see #EXTRA_BSSID 248 * @see #EXTRA_WIFI_INFO 249 */ 250 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) 251 public static final String NETWORK_STATE_CHANGED_ACTION = "android.net.wifi.STATE_CHANGE"; 252 /** 253 * The lookup key for a {@link android.net.NetworkInfo} object associated with the 254 * Wi-Fi network. Retrieve with 255 * {@link android.content.Intent#getParcelableExtra(String)}. 256 */ 257 public static final String EXTRA_NETWORK_INFO = "networkInfo"; 258 /** 259 * The lookup key for a String giving the BSSID of the access point to which 260 * we are connected. Only present when the new state is CONNECTED. 261 * Retrieve with 262 * {@link android.content.Intent#getStringExtra(String)}. 263 */ 264 public static final String EXTRA_BSSID = "bssid"; 265 /** 266 * The lookup key for a {@link android.net.wifi.WifiInfo} object giving the 267 * information about the access point to which we are connected. Only present 268 * when the new state is CONNECTED. Retrieve with 269 * {@link android.content.Intent#getParcelableExtra(String)}. 270 */ 271 public static final String EXTRA_WIFI_INFO = "wifiInfo"; 272 /** 273 * Broadcast intent action indicating that the state of establishing a connection to 274 * an access point has changed.One extra provides the new 275 * {@link SupplicantState}. Note that the supplicant state is Wi-Fi specific, and 276 * is not generally the most useful thing to look at if you are just interested in 277 * the overall state of connectivity. 278 * @see #EXTRA_NEW_STATE 279 * @see #EXTRA_SUPPLICANT_ERROR 280 */ 281 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) 282 public static final String SUPPLICANT_STATE_CHANGED_ACTION = 283 "android.net.wifi.supplicant.STATE_CHANGE"; 284 /** 285 * The lookup key for a {@link SupplicantState} describing the new state 286 * Retrieve with 287 * {@link android.content.Intent#getParcelableExtra(String)}. 288 */ 289 public static final String EXTRA_NEW_STATE = "newState"; 290 291 /** 292 * The lookup key for a {@link SupplicantState} describing the supplicant 293 * error code if any 294 * Retrieve with 295 * {@link android.content.Intent#getIntExtra(String, int)}. 296 * @see #ERROR_AUTHENTICATING 297 */ 298 public static final String EXTRA_SUPPLICANT_ERROR = "supplicantError"; 299 300 /** 301 * Broadcast intent action indicating that the configured networks changed. 302 * This can be as a result of adding/updating/deleting a network. If 303 * {@link #EXTRA_MULTIPLE_NETWORKS_CHANGED} is set to true the new configuration 304 * can be retreived with the {@link #EXTRA_WIFI_CONFIGURATION} extra. If multiple 305 * Wi-Fi configurations changed, {@link #EXTRA_WIFI_CONFIGURATION} will not be present. 306 * @hide 307 */ 308 public static final String CONFIGURED_NETWORKS_CHANGED_ACTION = 309 "android.net.wifi.CONFIGURED_NETWORKS_CHANGE"; 310 /** 311 * The lookup key for a (@link android.net.wifi.WifiConfiguration} object representing 312 * the changed Wi-Fi configuration when the {@link #CONFIGURED_NETWORKS_CHANGED_ACTION} 313 * broadcast is sent. 314 * @hide 315 */ 316 public static final String EXTRA_WIFI_CONFIGURATION = "wifiConfiguration"; 317 /** 318 * Multiple network configurations have changed. 319 * @see #CONFIGURED_NETWORKS_CHANGED_ACTION 320 * 321 * @hide 322 */ 323 public static final String EXTRA_MULTIPLE_NETWORKS_CHANGED = "multipleChanges"; 324 /** 325 * The lookup key for an integer indicating the reason a Wi-Fi network configuration 326 * has changed. Only present if {@link #EXTRA_MULTIPLE_NETWORKS_CHANGED} is {@code false} 327 * @see #CONFIGURED_NETWORKS_CHANGED_ACTION 328 * @hide 329 */ 330 public static final String EXTRA_CHANGE_REASON = "changeReason"; 331 /** 332 * The configuration is new and was added. 333 * @hide 334 */ 335 public static final int CHANGE_REASON_ADDED = 0; 336 /** 337 * The configuration was removed and is no longer present in the system's list of 338 * configured networks. 339 * @hide 340 */ 341 public static final int CHANGE_REASON_REMOVED = 1; 342 /** 343 * The configuration has changed as a result of explicit action or because the system 344 * took an automated action such as disabling a malfunctioning configuration. 345 * @hide 346 */ 347 public static final int CHANGE_REASON_CONFIG_CHANGE = 2; 348 /** 349 * An access point scan has completed, and results are available from the supplicant. 350 * Call {@link #getScanResults()} to obtain the results. 351 */ 352 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) 353 public static final String SCAN_RESULTS_AVAILABLE_ACTION = "android.net.wifi.SCAN_RESULTS"; 354 /** 355 * The RSSI (signal strength) has changed. 356 * @see #EXTRA_NEW_RSSI 357 */ 358 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) 359 public static final String RSSI_CHANGED_ACTION = "android.net.wifi.RSSI_CHANGED"; 360 /** 361 * The lookup key for an {@code int} giving the new RSSI in dBm. 362 */ 363 public static final String EXTRA_NEW_RSSI = "newRssi"; 364 365 /** 366 * Broadcast intent action indicating that the link configuration 367 * changed on wifi. 368 * @hide 369 */ 370 public static final String LINK_CONFIGURATION_CHANGED_ACTION = 371 "android.net.wifi.LINK_CONFIGURATION_CHANGED"; 372 373 /** 374 * The lookup key for a {@link android.net.LinkProperties} object associated with the 375 * Wi-Fi network. Retrieve with 376 * {@link android.content.Intent#getParcelableExtra(String)}. 377 * @hide 378 */ 379 public static final String EXTRA_LINK_PROPERTIES = "linkProperties"; 380 381 /** 382 * The lookup key for a {@link android.net.LinkCapabilities} object associated with the 383 * Wi-Fi network. Retrieve with 384 * {@link android.content.Intent#getParcelableExtra(String)}. 385 * @hide 386 */ 387 public static final String EXTRA_LINK_CAPABILITIES = "linkCapabilities"; 388 389 /** 390 * The network IDs of the configured networks could have changed. 391 */ 392 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) 393 public static final String NETWORK_IDS_CHANGED_ACTION = "android.net.wifi.NETWORK_IDS_CHANGED"; 394 395 /** 396 * Activity Action: Pick a Wi-Fi network to connect to. 397 * <p>Input: Nothing. 398 * <p>Output: Nothing. 399 */ 400 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION) 401 public static final String ACTION_PICK_WIFI_NETWORK = "android.net.wifi.PICK_WIFI_NETWORK"; 402 403 /** 404 * In this Wi-Fi lock mode, Wi-Fi will be kept active, 405 * and will behave normally, i.e., it will attempt to automatically 406 * establish a connection to a remembered access point that is 407 * within range, and will do periodic scans if there are remembered 408 * access points but none are in range. 409 */ 410 public static final int WIFI_MODE_FULL = 1; 411 /** 412 * In this Wi-Fi lock mode, Wi-Fi will be kept active, 413 * but the only operation that will be supported is initiation of 414 * scans, and the subsequent reporting of scan results. No attempts 415 * will be made to automatically connect to remembered access points, 416 * nor will periodic scans be automatically performed looking for 417 * remembered access points. Scans must be explicitly requested by 418 * an application in this mode. 419 */ 420 public static final int WIFI_MODE_SCAN_ONLY = 2; 421 /** 422 * In this Wi-Fi lock mode, Wi-Fi will be kept active as in mode 423 * {@link #WIFI_MODE_FULL} but it operates at high performance 424 * with minimum packet loss and low packet latency even when 425 * the device screen is off. This mode will consume more power 426 * and hence should be used only when there is a need for such 427 * an active connection. 428 * <p> 429 * An example use case is when a voice connection needs to be 430 * kept active even after the device screen goes off. Holding the 431 * regular {@link #WIFI_MODE_FULL} lock will keep the wifi 432 * connection active, but the connection can be lossy. 433 * Holding a {@link #WIFI_MODE_FULL_HIGH_PERF} lock for the 434 * duration of the voice call will improve the call quality. 435 * <p> 436 * When there is no support from the hardware, this lock mode 437 * will have the same behavior as {@link #WIFI_MODE_FULL} 438 */ 439 public static final int WIFI_MODE_FULL_HIGH_PERF = 3; 440 441 /** Anything worse than or equal to this will show 0 bars. */ 442 private static final int MIN_RSSI = -100; 443 444 /** Anything better than or equal to this will show the max bars. */ 445 private static final int MAX_RSSI = -55; 446 447 /** 448 * Number of RSSI levels used in the framework to initiate 449 * {@link #RSSI_CHANGED_ACTION} broadcast 450 * @hide 451 */ 452 public static final int RSSI_LEVELS = 5; 453 454 /** 455 * Auto settings in the driver. The driver could choose to operate on both 456 * 2.4 GHz and 5 GHz or make a dynamic decision on selecting the band. 457 * @hide 458 */ 459 public static final int WIFI_FREQUENCY_BAND_AUTO = 0; 460 461 /** 462 * Operation on 5 GHz alone 463 * @hide 464 */ 465 public static final int WIFI_FREQUENCY_BAND_5GHZ = 1; 466 467 /** 468 * Operation on 2.4 GHz alone 469 * @hide 470 */ 471 public static final int WIFI_FREQUENCY_BAND_2GHZ = 2; 472 473 /** List of asyncronous notifications 474 * @hide 475 */ 476 public static final int DATA_ACTIVITY_NOTIFICATION = 1; 477 478 //Lowest bit indicates data reception and the second lowest 479 //bit indicates data transmitted 480 /** @hide */ 481 public static final int DATA_ACTIVITY_NONE = 0x00; 482 /** @hide */ 483 public static final int DATA_ACTIVITY_IN = 0x01; 484 /** @hide */ 485 public static final int DATA_ACTIVITY_OUT = 0x02; 486 /** @hide */ 487 public static final int DATA_ACTIVITY_INOUT = 0x03; 488 489 /* Maximum number of active locks we allow. 490 * This limit was added to prevent apps from creating a ridiculous number 491 * of locks and crashing the system by overflowing the global ref table. 492 */ 493 private static final int MAX_ACTIVE_LOCKS = 50; 494 495 /* Number of currently active WifiLocks and MulticastLocks */ 496 private int mActiveLockCount; 497 498 private Context mContext; 499 IWifiManager mService; 500 501 private static final int INVALID_KEY = 0; 502 private int mListenerKey = 1; 503 private final SparseArray mListenerMap = new SparseArray(); 504 private final Object mListenerMapLock = new Object(); 505 506 private AsyncChannel mAsyncChannel = new AsyncChannel(); 507 private ServiceHandler mHandler; 508 private Messenger mWifiServiceMessenger; 509 private final CountDownLatch mConnected = new CountDownLatch(1); 510 511 /** 512 * Create a new WifiManager instance. 513 * Applications will almost always want to use 514 * {@link android.content.Context#getSystemService Context.getSystemService()} to retrieve 515 * the standard {@link android.content.Context#WIFI_SERVICE Context.WIFI_SERVICE}. 516 * @param context the application context 517 * @param service the Binder interface 518 * @hide - hide this because it takes in a parameter of type IWifiManager, which 519 * is a system private class. 520 */ 521 public WifiManager(Context context, IWifiManager service) { 522 mContext = context; 523 mService = service; 524 init(); 525 } 526 527 /** 528 * Return a list of all the networks configured in the supplicant. 529 * Not all fields of WifiConfiguration are returned. Only the following 530 * fields are filled in: 531 * <ul> 532 * <li>networkId</li> 533 * <li>SSID</li> 534 * <li>BSSID</li> 535 * <li>priority</li> 536 * <li>allowedProtocols</li> 537 * <li>allowedKeyManagement</li> 538 * <li>allowedAuthAlgorithms</li> 539 * <li>allowedPairwiseCiphers</li> 540 * <li>allowedGroupCiphers</li> 541 * </ul> 542 * @return a list of network configurations in the form of a list 543 * of {@link WifiConfiguration} objects. 544 */ 545 public List<WifiConfiguration> getConfiguredNetworks() { 546 try { 547 return mService.getConfiguredNetworks(); 548 } catch (RemoteException e) { 549 return null; 550 } 551 } 552 553 /** 554 * Add a new network description to the set of configured networks. 555 * The {@code networkId} field of the supplied configuration object 556 * is ignored. 557 * <p/> 558 * The new network will be marked DISABLED by default. To enable it, 559 * called {@link #enableNetwork}. 560 * 561 * @param config the set of variables that describe the configuration, 562 * contained in a {@link WifiConfiguration} object. 563 * @return the ID of the newly created network description. This is used in 564 * other operations to specified the network to be acted upon. 565 * Returns {@code -1} on failure. 566 */ 567 public int addNetwork(WifiConfiguration config) { 568 if (config == null) { 569 return -1; 570 } 571 config.networkId = -1; 572 return addOrUpdateNetwork(config); 573 } 574 575 /** 576 * Update the network description of an existing configured network. 577 * 578 * @param config the set of variables that describe the configuration, 579 * contained in a {@link WifiConfiguration} object. It may 580 * be sparse, so that only the items that are being changed 581 * are non-<code>null</code>. The {@code networkId} field 582 * must be set to the ID of the existing network being updated. 583 * @return Returns the {@code networkId} of the supplied 584 * {@code WifiConfiguration} on success. 585 * <br/> 586 * Returns {@code -1} on failure, including when the {@code networkId} 587 * field of the {@code WifiConfiguration} does not refer to an 588 * existing network. 589 */ 590 public int updateNetwork(WifiConfiguration config) { 591 if (config == null || config.networkId < 0) { 592 return -1; 593 } 594 return addOrUpdateNetwork(config); 595 } 596 597 /** 598 * Internal method for doing the RPC that creates a new network description 599 * or updates an existing one. 600 * 601 * @param config The possibly sparse object containing the variables that 602 * are to set or updated in the network description. 603 * @return the ID of the network on success, {@code -1} on failure. 604 */ 605 private int addOrUpdateNetwork(WifiConfiguration config) { 606 try { 607 return mService.addOrUpdateNetwork(config); 608 } catch (RemoteException e) { 609 return -1; 610 } 611 } 612 613 /** 614 * Remove the specified network from the list of configured networks. 615 * This may result in the asynchronous delivery of state change 616 * events. 617 * @param netId the integer that identifies the network configuration 618 * to the supplicant 619 * @return {@code true} if the operation succeeded 620 */ 621 public boolean removeNetwork(int netId) { 622 try { 623 return mService.removeNetwork(netId); 624 } catch (RemoteException e) { 625 return false; 626 } 627 } 628 629 /** 630 * Allow a previously configured network to be associated with. If 631 * <code>disableOthers</code> is true, then all other configured 632 * networks are disabled, and an attempt to connect to the selected 633 * network is initiated. This may result in the asynchronous delivery 634 * of state change events. 635 * @param netId the ID of the network in the list of configured networks 636 * @param disableOthers if true, disable all other networks. The way to 637 * select a particular network to connect to is specify {@code true} 638 * for this parameter. 639 * @return {@code true} if the operation succeeded 640 */ 641 public boolean enableNetwork(int netId, boolean disableOthers) { 642 try { 643 return mService.enableNetwork(netId, disableOthers); 644 } catch (RemoteException e) { 645 return false; 646 } 647 } 648 649 /** 650 * Disable a configured network. The specified network will not be 651 * a candidate for associating. This may result in the asynchronous 652 * delivery of state change events. 653 * @param netId the ID of the network as returned by {@link #addNetwork}. 654 * @return {@code true} if the operation succeeded 655 */ 656 public boolean disableNetwork(int netId) { 657 try { 658 return mService.disableNetwork(netId); 659 } catch (RemoteException e) { 660 return false; 661 } 662 } 663 664 /** 665 * Disassociate from the currently active access point. This may result 666 * in the asynchronous delivery of state change events. 667 * @return {@code true} if the operation succeeded 668 */ 669 public boolean disconnect() { 670 try { 671 mService.disconnect(); 672 return true; 673 } catch (RemoteException e) { 674 return false; 675 } 676 } 677 678 /** 679 * Reconnect to the currently active access point, if we are currently 680 * disconnected. This may result in the asynchronous delivery of state 681 * change events. 682 * @return {@code true} if the operation succeeded 683 */ 684 public boolean reconnect() { 685 try { 686 mService.reconnect(); 687 return true; 688 } catch (RemoteException e) { 689 return false; 690 } 691 } 692 693 /** 694 * Reconnect to the currently active access point, even if we are already 695 * connected. This may result in the asynchronous delivery of state 696 * change events. 697 * @return {@code true} if the operation succeeded 698 */ 699 public boolean reassociate() { 700 try { 701 mService.reassociate(); 702 return true; 703 } catch (RemoteException e) { 704 return false; 705 } 706 } 707 708 /** 709 * Check that the supplicant daemon is responding to requests. 710 * @return {@code true} if we were able to communicate with the supplicant and 711 * it returned the expected response to the PING message. 712 */ 713 public boolean pingSupplicant() { 714 if (mService == null) 715 return false; 716 try { 717 return mService.pingSupplicant(); 718 } catch (RemoteException e) { 719 return false; 720 } 721 } 722 723 /** 724 * Request a scan for access points. Returns immediately. The availability 725 * of the results is made known later by means of an asynchronous event sent 726 * on completion of the scan. 727 * @return {@code true} if the operation succeeded, i.e., the scan was initiated 728 */ 729 public boolean startScan() { 730 try { 731 mService.startScan(false); 732 return true; 733 } catch (RemoteException e) { 734 return false; 735 } 736 } 737 738 /** 739 * Request a scan for access points. Returns immediately. The availability 740 * of the results is made known later by means of an asynchronous event sent 741 * on completion of the scan. 742 * This is a variant of startScan that forces an active scan, even if passive 743 * scans are the current default 744 * @return {@code true} if the operation succeeded, i.e., the scan was initiated 745 * 746 * @hide 747 */ 748 public boolean startScanActive() { 749 try { 750 mService.startScan(true); 751 return true; 752 } catch (RemoteException e) { 753 return false; 754 } 755 } 756 757 /** 758 * Return dynamic information about the current Wi-Fi connection, if any is active. 759 * @return the Wi-Fi information, contained in {@link WifiInfo}. 760 */ 761 public WifiInfo getConnectionInfo() { 762 try { 763 return mService.getConnectionInfo(); 764 } catch (RemoteException e) { 765 return null; 766 } 767 } 768 769 /** 770 * Return the results of the latest access point scan. 771 * @return the list of access points found in the most recent scan. 772 */ 773 public List<ScanResult> getScanResults() { 774 try { 775 return mService.getScanResults(); 776 } catch (RemoteException e) { 777 return null; 778 } 779 } 780 781 /** 782 * Tell the supplicant to persist the current list of configured networks. 783 * <p> 784 * Note: It is possible for this method to change the network IDs of 785 * existing networks. You should assume the network IDs can be different 786 * after calling this method. 787 * 788 * @return {@code true} if the operation succeeded 789 */ 790 public boolean saveConfiguration() { 791 try { 792 return mService.saveConfiguration(); 793 } catch (RemoteException e) { 794 return false; 795 } 796 } 797 798 /** 799 * Set the country code. 800 * @param countryCode country code in ISO 3166 format. 801 * @param persist {@code true} if this needs to be remembered 802 * 803 * @hide 804 */ 805 public void setCountryCode(String country, boolean persist) { 806 try { 807 mService.setCountryCode(country, persist); 808 } catch (RemoteException e) { } 809 } 810 811 /** 812 * Set the operational frequency band. 813 * @param band One of 814 * {@link #WIFI_FREQUENCY_BAND_AUTO}, 815 * {@link #WIFI_FREQUENCY_BAND_5GHZ}, 816 * {@link #WIFI_FREQUENCY_BAND_2GHZ}, 817 * @param persist {@code true} if this needs to be remembered 818 * @hide 819 */ 820 public void setFrequencyBand(int band, boolean persist) { 821 try { 822 mService.setFrequencyBand(band, persist); 823 } catch (RemoteException e) { } 824 } 825 826 /** 827 * Get the operational frequency band. 828 * @return One of 829 * {@link #WIFI_FREQUENCY_BAND_AUTO}, 830 * {@link #WIFI_FREQUENCY_BAND_5GHZ}, 831 * {@link #WIFI_FREQUENCY_BAND_2GHZ} or 832 * {@code -1} on failure. 833 * @hide 834 */ 835 public int getFrequencyBand() { 836 try { 837 return mService.getFrequencyBand(); 838 } catch (RemoteException e) { 839 return -1; 840 } 841 } 842 843 /** 844 * Check if the chipset supports dual frequency band (2.4 GHz and 5 GHz) 845 * @return {@code true} if supported, {@code false} otherwise. 846 * @hide 847 */ 848 public boolean isDualBandSupported() { 849 try { 850 return mService.isDualBandSupported(); 851 } catch (RemoteException e) { 852 return false; 853 } 854 } 855 856 /** 857 * Return the DHCP-assigned addresses from the last successful DHCP request, 858 * if any. 859 * @return the DHCP information 860 */ 861 public DhcpInfo getDhcpInfo() { 862 try { 863 return mService.getDhcpInfo(); 864 } catch (RemoteException e) { 865 return null; 866 } 867 } 868 869 870 /** 871 * Enable or disable Wi-Fi. 872 * @param enabled {@code true} to enable, {@code false} to disable. 873 * @return {@code true} if the operation succeeds (or if the existing state 874 * is the same as the requested state). 875 */ 876 public boolean setWifiEnabled(boolean enabled) { 877 try { 878 return mService.setWifiEnabled(enabled); 879 } catch (RemoteException e) { 880 return false; 881 } 882 } 883 884 /** 885 * Gets the Wi-Fi enabled state. 886 * @return One of {@link #WIFI_STATE_DISABLED}, 887 * {@link #WIFI_STATE_DISABLING}, {@link #WIFI_STATE_ENABLED}, 888 * {@link #WIFI_STATE_ENABLING}, {@link #WIFI_STATE_UNKNOWN} 889 * @see #isWifiEnabled() 890 */ 891 public int getWifiState() { 892 try { 893 return mService.getWifiEnabledState(); 894 } catch (RemoteException e) { 895 return WIFI_STATE_UNKNOWN; 896 } 897 } 898 899 /** 900 * Return whether Wi-Fi is enabled or disabled. 901 * @return {@code true} if Wi-Fi is enabled 902 * @see #getWifiState() 903 */ 904 public boolean isWifiEnabled() { 905 return getWifiState() == WIFI_STATE_ENABLED; 906 } 907 908 /** 909 * Return TX packet counter, for CTS test of WiFi watchdog. 910 * @param listener is the interface to receive result 911 * 912 * @hide for CTS test only 913 */ 914 public void getTxPacketCount(TxPacketCountListener listener) { 915 validateChannel(); 916 mAsyncChannel.sendMessage(RSSI_PKTCNT_FETCH, 0, putListener(listener)); 917 } 918 919 /** 920 * Calculates the level of the signal. This should be used any time a signal 921 * is being shown. 922 * 923 * @param rssi The power of the signal measured in RSSI. 924 * @param numLevels The number of levels to consider in the calculated 925 * level. 926 * @return A level of the signal, given in the range of 0 to numLevels-1 927 * (both inclusive). 928 */ 929 public static int calculateSignalLevel(int rssi, int numLevels) { 930 if (rssi <= MIN_RSSI) { 931 return 0; 932 } else if (rssi >= MAX_RSSI) { 933 return numLevels - 1; 934 } else { 935 float inputRange = (MAX_RSSI - MIN_RSSI); 936 float outputRange = (numLevels - 1); 937 return (int)((float)(rssi - MIN_RSSI) * outputRange / inputRange); 938 } 939 } 940 941 /** 942 * Compares two signal strengths. 943 * 944 * @param rssiA The power of the first signal measured in RSSI. 945 * @param rssiB The power of the second signal measured in RSSI. 946 * @return Returns <0 if the first signal is weaker than the second signal, 947 * 0 if the two signals have the same strength, and >0 if the first 948 * signal is stronger than the second signal. 949 */ 950 public static int compareSignalLevel(int rssiA, int rssiB) { 951 return rssiA - rssiB; 952 } 953 954 /** 955 * Start AccessPoint mode with the specified 956 * configuration. If the radio is already running in 957 * AP mode, update the new configuration 958 * Note that starting in access point mode disables station 959 * mode operation 960 * @param wifiConfig SSID, security and channel details as 961 * part of WifiConfiguration 962 * @return {@code true} if the operation succeeds, {@code false} otherwise 963 * 964 * @hide Dont open up yet 965 */ 966 public boolean setWifiApEnabled(WifiConfiguration wifiConfig, boolean enabled) { 967 try { 968 mService.setWifiApEnabled(wifiConfig, enabled); 969 return true; 970 } catch (RemoteException e) { 971 return false; 972 } 973 } 974 975 /** 976 * Gets the Wi-Fi enabled state. 977 * @return One of {@link #WIFI_AP_STATE_DISABLED}, 978 * {@link #WIFI_AP_STATE_DISABLING}, {@link #WIFI_AP_STATE_ENABLED}, 979 * {@link #WIFI_AP_STATE_ENABLING}, {@link #WIFI_AP_STATE_FAILED} 980 * @see #isWifiApEnabled() 981 * 982 * @hide Dont open yet 983 */ 984 public int getWifiApState() { 985 try { 986 return mService.getWifiApEnabledState(); 987 } catch (RemoteException e) { 988 return WIFI_AP_STATE_FAILED; 989 } 990 } 991 992 /** 993 * Return whether Wi-Fi AP is enabled or disabled. 994 * @return {@code true} if Wi-Fi AP is enabled 995 * @see #getWifiApState() 996 * 997 * @hide Dont open yet 998 */ 999 public boolean isWifiApEnabled() { 1000 return getWifiApState() == WIFI_AP_STATE_ENABLED; 1001 } 1002 1003 /** 1004 * Gets the Wi-Fi AP Configuration. 1005 * @return AP details in WifiConfiguration 1006 * 1007 * @hide Dont open yet 1008 */ 1009 public WifiConfiguration getWifiApConfiguration() { 1010 try { 1011 return mService.getWifiApConfiguration(); 1012 } catch (RemoteException e) { 1013 return null; 1014 } 1015 } 1016 1017 /** 1018 * Sets the Wi-Fi AP Configuration. 1019 * @return {@code true} if the operation succeeded, {@code false} otherwise 1020 * 1021 * @hide Dont open yet 1022 */ 1023 public boolean setWifiApConfiguration(WifiConfiguration wifiConfig) { 1024 try { 1025 mService.setWifiApConfiguration(wifiConfig); 1026 return true; 1027 } catch (RemoteException e) { 1028 return false; 1029 } 1030 } 1031 1032 /** 1033 * Start the driver and connect to network. 1034 * 1035 * This function will over-ride WifiLock and device idle status. For example, 1036 * even if the device is idle or there is only a scan-only lock held, 1037 * a start wifi would mean that wifi connection is kept active until 1038 * a stopWifi() is sent. 1039 * 1040 * This API is used by WifiStateTracker 1041 * 1042 * @return {@code true} if the operation succeeds else {@code false} 1043 * @hide 1044 */ 1045 public boolean startWifi() { 1046 try { 1047 mService.startWifi(); 1048 return true; 1049 } catch (RemoteException e) { 1050 return false; 1051 } 1052 } 1053 1054 /** 1055 * Disconnect from a network (if any) and stop the driver. 1056 * 1057 * This function will over-ride WifiLock and device idle status. Wi-Fi 1058 * stays inactive until a startWifi() is issued. 1059 * 1060 * This API is used by WifiStateTracker 1061 * 1062 * @return {@code true} if the operation succeeds else {@code false} 1063 * @hide 1064 */ 1065 public boolean stopWifi() { 1066 try { 1067 mService.stopWifi(); 1068 return true; 1069 } catch (RemoteException e) { 1070 return false; 1071 } 1072 } 1073 1074 /** 1075 * Add a bssid to the supplicant blacklist 1076 * 1077 * This API is used by WifiWatchdogService 1078 * 1079 * @return {@code true} if the operation succeeds else {@code false} 1080 * @hide 1081 */ 1082 public boolean addToBlacklist(String bssid) { 1083 try { 1084 mService.addToBlacklist(bssid); 1085 return true; 1086 } catch (RemoteException e) { 1087 return false; 1088 } 1089 } 1090 1091 /** 1092 * Clear the supplicant blacklist 1093 * 1094 * This API is used by WifiWatchdogService 1095 * 1096 * @return {@code true} if the operation succeeds else {@code false} 1097 * @hide 1098 */ 1099 public boolean clearBlacklist() { 1100 try { 1101 mService.clearBlacklist(); 1102 return true; 1103 } catch (RemoteException e) { 1104 return false; 1105 } 1106 } 1107 1108 /* TODO: deprecate synchronous API and open up the following API */ 1109 1110 private static final int BASE = Protocol.BASE_WIFI_MANAGER; 1111 1112 /* Commands to WifiService */ 1113 /** @hide */ 1114 public static final int CONNECT_NETWORK = BASE + 1; 1115 /** @hide */ 1116 public static final int CONNECT_NETWORK_FAILED = BASE + 2; 1117 /** @hide */ 1118 public static final int CONNECT_NETWORK_SUCCEEDED = BASE + 3; 1119 1120 /** @hide */ 1121 public static final int FORGET_NETWORK = BASE + 4; 1122 /** @hide */ 1123 public static final int FORGET_NETWORK_FAILED = BASE + 5; 1124 /** @hide */ 1125 public static final int FORGET_NETWORK_SUCCEEDED = BASE + 6; 1126 1127 /** @hide */ 1128 public static final int SAVE_NETWORK = BASE + 7; 1129 /** @hide */ 1130 public static final int SAVE_NETWORK_FAILED = BASE + 8; 1131 /** @hide */ 1132 public static final int SAVE_NETWORK_SUCCEEDED = BASE + 9; 1133 1134 /** @hide */ 1135 public static final int START_WPS = BASE + 10; 1136 /** @hide */ 1137 public static final int START_WPS_SUCCEEDED = BASE + 11; 1138 /** @hide */ 1139 public static final int WPS_FAILED = BASE + 12; 1140 /** @hide */ 1141 public static final int WPS_COMPLETED = BASE + 13; 1142 1143 /** @hide */ 1144 public static final int CANCEL_WPS = BASE + 14; 1145 /** @hide */ 1146 public static final int CANCEL_WPS_FAILED = BASE + 15; 1147 /** @hide */ 1148 public static final int CANCEL_WPS_SUCCEDED = BASE + 16; 1149 1150 /** @hide */ 1151 public static final int DISABLE_NETWORK = BASE + 17; 1152 /** @hide */ 1153 public static final int DISABLE_NETWORK_FAILED = BASE + 18; 1154 /** @hide */ 1155 public static final int DISABLE_NETWORK_SUCCEEDED = BASE + 19; 1156 1157 /** @hide */ 1158 public static final int RSSI_PKTCNT_FETCH = BASE + 20; 1159 /** @hide */ 1160 public static final int RSSI_PKTCNT_FETCH_SUCCEEDED = BASE + 21; 1161 /** @hide */ 1162 public static final int RSSI_PKTCNT_FETCH_FAILED = BASE + 22; 1163 1164 /* For system use only */ 1165 /** @hide */ 1166 public static final int ENABLE_TRAFFIC_STATS_POLL = BASE + 31; 1167 /** @hide */ 1168 public static final int TRAFFIC_STATS_POLL = BASE + 32; 1169 1170 1171 /** 1172 * Passed with {@link ActionListener#onFailure}. 1173 * Indicates that the operation failed due to an internal error. 1174 * @hide 1175 */ 1176 public static final int ERROR = 0; 1177 1178 /** 1179 * Passed with {@link ActionListener#onFailure}. 1180 * Indicates that the operation is already in progress 1181 * @hide 1182 */ 1183 public static final int IN_PROGRESS = 1; 1184 1185 /** 1186 * Passed with {@link ActionListener#onFailure}. 1187 * Indicates that the operation failed because the framework is busy and 1188 * unable to service the request 1189 * @hide 1190 */ 1191 public static final int BUSY = 2; 1192 1193 /* WPS specific errors */ 1194 /** WPS overlap detected {@hide} */ 1195 public static final int WPS_OVERLAP_ERROR = 3; 1196 /** WEP on WPS is prohibited {@hide} */ 1197 public static final int WPS_WEP_PROHIBITED = 4; 1198 /** TKIP only prohibited {@hide} */ 1199 public static final int WPS_TKIP_ONLY_PROHIBITED = 5; 1200 /** Authentication failure on WPS {@hide} */ 1201 public static final int WPS_AUTH_FAILURE = 6; 1202 /** WPS timed out {@hide} */ 1203 public static final int WPS_TIMED_OUT = 7; 1204 1205 /** Interface for callback invocation on an application action {@hide} */ 1206 public interface ActionListener { 1207 /** The operation succeeded */ 1208 public void onSuccess(); 1209 /** 1210 * The operation failed 1211 * @param reason The reason for failure could be one of 1212 * {@link #ERROR}, {@link #IN_PROGRESS} or {@link #BUSY} 1213 */ 1214 public void onFailure(int reason); 1215 } 1216 1217 /** Interface for callback invocation on a start WPS action {@hide} */ 1218 public interface WpsListener { 1219 /** WPS start succeeded */ 1220 public void onStartSuccess(String pin); 1221 1222 /** WPS operation completed succesfully */ 1223 public void onCompletion(); 1224 1225 /** 1226 * WPS operation failed 1227 * @param reason The reason for failure could be one of 1228 * {@link #IN_PROGRESS}, {@link #WPS_OVERLAP_ERROR},{@link #ERROR} or {@link #BUSY} 1229 */ 1230 public void onFailure(int reason); 1231 } 1232 1233 /** Interface for callback invocation on a TX packet count poll action {@hide} */ 1234 public interface TxPacketCountListener { 1235 /** 1236 * The operation succeeded 1237 * @param count TX packet counter 1238 */ 1239 public void onSuccess(int count); 1240 /** 1241 * The operation failed 1242 * @param reason The reason for failure could be one of 1243 * {@link #ERROR}, {@link #IN_PROGRESS} or {@link #BUSY} 1244 */ 1245 public void onFailure(int reason); 1246 } 1247 1248 private class ServiceHandler extends Handler { 1249 ServiceHandler(Looper looper) { 1250 super(looper); 1251 } 1252 1253 @Override 1254 public void handleMessage(Message message) { 1255 Object listener = removeListener(message.arg2); 1256 switch (message.what) { 1257 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: 1258 if (message.arg1 == AsyncChannel.STATUS_SUCCESSFUL) { 1259 mAsyncChannel.sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION); 1260 } else { 1261 Log.e(TAG, "Failed to set up channel connection"); 1262 // This will cause all further async API calls on the WifiManager 1263 // to fail and throw an exception 1264 mAsyncChannel = null; 1265 } 1266 mConnected.countDown(); 1267 break; 1268 case AsyncChannel.CMD_CHANNEL_FULLY_CONNECTED: 1269 // Ignore 1270 break; 1271 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: 1272 Log.e(TAG, "Channel connection lost"); 1273 // This will cause all further async API calls on the WifiManager 1274 // to fail and throw an exception 1275 mAsyncChannel = null; 1276 break; 1277 /* ActionListeners grouped together */ 1278 case WifiManager.CONNECT_NETWORK_FAILED: 1279 case WifiManager.FORGET_NETWORK_FAILED: 1280 case WifiManager.SAVE_NETWORK_FAILED: 1281 case WifiManager.CANCEL_WPS_FAILED: 1282 case WifiManager.DISABLE_NETWORK_FAILED: 1283 if (listener != null) { 1284 ((ActionListener) listener).onFailure(message.arg1); 1285 } 1286 break; 1287 /* ActionListeners grouped together */ 1288 case WifiManager.CONNECT_NETWORK_SUCCEEDED: 1289 case WifiManager.FORGET_NETWORK_SUCCEEDED: 1290 case WifiManager.SAVE_NETWORK_SUCCEEDED: 1291 case WifiManager.CANCEL_WPS_SUCCEDED: 1292 case WifiManager.DISABLE_NETWORK_SUCCEEDED: 1293 if (listener != null) { 1294 ((ActionListener) listener).onSuccess(); 1295 } 1296 break; 1297 case WifiManager.START_WPS_SUCCEEDED: 1298 if (listener != null) { 1299 WpsResult result = (WpsResult) message.obj; 1300 ((WpsListener) listener).onStartSuccess(result.pin); 1301 //Listener needs to stay until completion or failure 1302 synchronized(mListenerMapLock) { 1303 mListenerMap.put(message.arg2, listener); 1304 } 1305 } 1306 break; 1307 case WifiManager.WPS_COMPLETED: 1308 if (listener != null) { 1309 ((WpsListener) listener).onCompletion(); 1310 } 1311 break; 1312 case WifiManager.WPS_FAILED: 1313 if (listener != null) { 1314 ((WpsListener) listener).onFailure(message.arg1); 1315 } 1316 break; 1317 case WifiManager.RSSI_PKTCNT_FETCH_SUCCEEDED: 1318 if (listener != null) { 1319 RssiPacketCountInfo info = (RssiPacketCountInfo) message.obj; 1320 if (info != null) 1321 ((TxPacketCountListener) listener).onSuccess(info.txgood + info.txbad); 1322 else 1323 ((TxPacketCountListener) listener).onFailure(ERROR); 1324 } 1325 break; 1326 case WifiManager.RSSI_PKTCNT_FETCH_FAILED: 1327 if (listener != null) { 1328 ((TxPacketCountListener) listener).onFailure(message.arg1); 1329 } 1330 break; 1331 default: 1332 //ignore 1333 break; 1334 } 1335 } 1336 } 1337 1338 private int putListener(Object listener) { 1339 if (listener == null) return INVALID_KEY; 1340 int key; 1341 synchronized (mListenerMapLock) { 1342 do { 1343 key = mListenerKey++; 1344 } while (key == INVALID_KEY); 1345 mListenerMap.put(key, listener); 1346 } 1347 return key; 1348 } 1349 1350 private Object removeListener(int key) { 1351 if (key == INVALID_KEY) return null; 1352 synchronized (mListenerMapLock) { 1353 Object listener = mListenerMap.get(key); 1354 mListenerMap.remove(key); 1355 return listener; 1356 } 1357 } 1358 1359 private void init() { 1360 mWifiServiceMessenger = getWifiServiceMessenger(); 1361 if (mWifiServiceMessenger == null) throw new RuntimeException("Failed to initialize"); 1362 HandlerThread t = new HandlerThread("WifiManager"); 1363 t.start(); 1364 mHandler = new ServiceHandler(t.getLooper()); 1365 mAsyncChannel.connect(mContext, mHandler, mWifiServiceMessenger); 1366 try { 1367 mConnected.await(); 1368 } catch (InterruptedException e) { 1369 Log.e(TAG, "interrupted wait at init"); 1370 } 1371 } 1372 1373 private void validateChannel() { 1374 if (mAsyncChannel == null) throw new IllegalStateException( 1375 "Bad WifiManager instance state, re-initialize"); 1376 } 1377 1378 /** 1379 * Connect to a network with the given configuration. The network also 1380 * gets added to the supplicant configuration. 1381 * 1382 * For a new network, this function is used instead of a 1383 * sequence of addNetwork(), enableNetwork(), saveConfiguration() and 1384 * reconnect() 1385 * 1386 * @param config the set of variables that describe the configuration, 1387 * contained in a {@link WifiConfiguration} object. 1388 * @param listener for callbacks on success or failure. Can be null. 1389 * @throws IllegalStateException if the WifiManager instance needs to be 1390 * initialized again 1391 * 1392 * @hide 1393 */ 1394 public void connect(WifiConfiguration config, ActionListener listener) { 1395 if (config == null) throw new IllegalArgumentException("config cannot be null"); 1396 validateChannel(); 1397 // Use INVALID_NETWORK_ID for arg1 when passing a config object 1398 // arg1 is used to pass network id when the network already exists 1399 mAsyncChannel.sendMessage(CONNECT_NETWORK, WifiConfiguration.INVALID_NETWORK_ID, 1400 putListener(listener), config); 1401 } 1402 1403 /** 1404 * Connect to a network with the given networkId. 1405 * 1406 * This function is used instead of a enableNetwork(), saveConfiguration() and 1407 * reconnect() 1408 * 1409 * @param networkId the network id identifiying the network in the 1410 * supplicant configuration list 1411 * @param listener for callbacks on success or failure. Can be null. 1412 * @throws IllegalStateException if the WifiManager instance needs to be 1413 * initialized again 1414 * @hide 1415 */ 1416 public void connect(int networkId, ActionListener listener) { 1417 if (networkId < 0) throw new IllegalArgumentException("Network id cannot be negative"); 1418 validateChannel(); 1419 mAsyncChannel.sendMessage(CONNECT_NETWORK, networkId, putListener(listener)); 1420 } 1421 1422 /** 1423 * Save the given network in the supplicant config. If the network already 1424 * exists, the configuration is updated. A new network is enabled 1425 * by default. 1426 * 1427 * For a new network, this function is used instead of a 1428 * sequence of addNetwork(), enableNetwork() and saveConfiguration(). 1429 * 1430 * For an existing network, it accomplishes the task of updateNetwork() 1431 * and saveConfiguration() 1432 * 1433 * @param config the set of variables that describe the configuration, 1434 * contained in a {@link WifiConfiguration} object. 1435 * @param listener for callbacks on success or failure. Can be null. 1436 * @throws IllegalStateException if the WifiManager instance needs to be 1437 * initialized again 1438 * @hide 1439 */ 1440 public void save(WifiConfiguration config, ActionListener listener) { 1441 if (config == null) throw new IllegalArgumentException("config cannot be null"); 1442 validateChannel(); 1443 mAsyncChannel.sendMessage(SAVE_NETWORK, 0, putListener(listener), config); 1444 } 1445 1446 /** 1447 * Delete the network in the supplicant config. 1448 * 1449 * This function is used instead of a sequence of removeNetwork() 1450 * and saveConfiguration(). 1451 * 1452 * @param config the set of variables that describe the configuration, 1453 * contained in a {@link WifiConfiguration} object. 1454 * @param listener for callbacks on success or failure. Can be null. 1455 * @throws IllegalStateException if the WifiManager instance needs to be 1456 * initialized again 1457 * @hide 1458 */ 1459 public void forget(int netId, ActionListener listener) { 1460 if (netId < 0) throw new IllegalArgumentException("Network id cannot be negative"); 1461 validateChannel(); 1462 mAsyncChannel.sendMessage(FORGET_NETWORK, netId, putListener(listener)); 1463 } 1464 1465 /** 1466 * Disable network 1467 * 1468 * @param netId is the network Id 1469 * @param listener for callbacks on success or failure. Can be null. 1470 * @throws IllegalStateException if the WifiManager instance needs to be 1471 * initialized again 1472 * @hide 1473 */ 1474 public void disable(int netId, ActionListener listener) { 1475 if (netId < 0) throw new IllegalArgumentException("Network id cannot be negative"); 1476 validateChannel(); 1477 mAsyncChannel.sendMessage(DISABLE_NETWORK, netId, putListener(listener)); 1478 } 1479 1480 /** 1481 * Start Wi-fi Protected Setup 1482 * 1483 * @param config WPS configuration 1484 * @param listener for callbacks on success or failure. Can be null. 1485 * @throws IllegalStateException if the WifiManager instance needs to be 1486 * initialized again 1487 * @hide 1488 */ 1489 public void startWps(WpsInfo config, WpsListener listener) { 1490 if (config == null) throw new IllegalArgumentException("config cannot be null"); 1491 validateChannel(); 1492 mAsyncChannel.sendMessage(START_WPS, 0, putListener(listener), config); 1493 } 1494 1495 /** 1496 * Cancel any ongoing Wi-fi Protected Setup 1497 * 1498 * @param listener for callbacks on success or failure. Can be null. 1499 * @throws IllegalStateException if the WifiManager instance needs to be 1500 * initialized again 1501 * @hide 1502 */ 1503 public void cancelWps(ActionListener listener) { 1504 validateChannel(); 1505 mAsyncChannel.sendMessage(CANCEL_WPS, 0, putListener(listener)); 1506 } 1507 1508 /** 1509 * Get a reference to WifiService handler. This is used by a client to establish 1510 * an AsyncChannel communication with WifiService 1511 * 1512 * @return Messenger pointing to the WifiService handler 1513 * @hide 1514 */ 1515 public Messenger getWifiServiceMessenger() { 1516 try { 1517 return mService.getWifiServiceMessenger(); 1518 } catch (RemoteException e) { 1519 return null; 1520 } 1521 } 1522 1523 /** 1524 * Get a reference to WifiStateMachine handler. 1525 * @return Messenger pointing to the WifiService handler 1526 * @hide 1527 */ 1528 public Messenger getWifiStateMachineMessenger() { 1529 try { 1530 return mService.getWifiStateMachineMessenger(); 1531 } catch (RemoteException e) { 1532 return null; 1533 } 1534 } 1535 1536 /** 1537 * Returns the file in which IP and proxy configuration data is stored 1538 * @hide 1539 */ 1540 public String getConfigFile() { 1541 try { 1542 return mService.getConfigFile(); 1543 } catch (RemoteException e) { 1544 return null; 1545 } 1546 } 1547 1548 /** 1549 * Allows an application to keep the Wi-Fi radio awake. 1550 * Normally the Wi-Fi radio may turn off when the user has not used the device in a while. 1551 * Acquiring a WifiLock will keep the radio on until the lock is released. Multiple 1552 * applications may hold WifiLocks, and the radio will only be allowed to turn off when no 1553 * WifiLocks are held in any application. 1554 * <p> 1555 * Before using a WifiLock, consider carefully if your application requires Wi-Fi access, or 1556 * could function over a mobile network, if available. A program that needs to download large 1557 * files should hold a WifiLock to ensure that the download will complete, but a program whose 1558 * network usage is occasional or low-bandwidth should not hold a WifiLock to avoid adversely 1559 * affecting battery life. 1560 * <p> 1561 * Note that WifiLocks cannot override the user-level "Wi-Fi Enabled" setting, nor Airplane 1562 * Mode. They simply keep the radio from turning off when Wi-Fi is already on but the device 1563 * is idle. 1564 * <p> 1565 * Any application using a WifiLock must request the {@code android.permission.WAKE_LOCK} 1566 * permission in an {@code <uses-permission>} element of the application's manifest. 1567 */ 1568 public class WifiLock { 1569 private String mTag; 1570 private final IBinder mBinder; 1571 private int mRefCount; 1572 int mLockType; 1573 private boolean mRefCounted; 1574 private boolean mHeld; 1575 private WorkSource mWorkSource; 1576 1577 private WifiLock(int lockType, String tag) { 1578 mTag = tag; 1579 mLockType = lockType; 1580 mBinder = new Binder(); 1581 mRefCount = 0; 1582 mRefCounted = true; 1583 mHeld = false; 1584 } 1585 1586 /** 1587 * Locks the Wi-Fi radio on until {@link #release} is called. 1588 * 1589 * If this WifiLock is reference-counted, each call to {@code acquire} will increment the 1590 * reference count, and the radio will remain locked as long as the reference count is 1591 * above zero. 1592 * 1593 * If this WifiLock is not reference-counted, the first call to {@code acquire} will lock 1594 * the radio, but subsequent calls will be ignored. Only one call to {@link #release} 1595 * will be required, regardless of the number of times that {@code acquire} is called. 1596 */ 1597 public void acquire() { 1598 synchronized (mBinder) { 1599 if (mRefCounted ? (++mRefCount == 1) : (!mHeld)) { 1600 try { 1601 mService.acquireWifiLock(mBinder, mLockType, mTag, mWorkSource); 1602 synchronized (WifiManager.this) { 1603 if (mActiveLockCount >= MAX_ACTIVE_LOCKS) { 1604 mService.releaseWifiLock(mBinder); 1605 throw new UnsupportedOperationException( 1606 "Exceeded maximum number of wifi locks"); 1607 } 1608 mActiveLockCount++; 1609 } 1610 } catch (RemoteException ignore) { 1611 } 1612 mHeld = true; 1613 } 1614 } 1615 } 1616 1617 /** 1618 * Unlocks the Wi-Fi radio, allowing it to turn off when the device is idle. 1619 * 1620 * If this WifiLock is reference-counted, each call to {@code release} will decrement the 1621 * reference count, and the radio will be unlocked only when the reference count reaches 1622 * zero. If the reference count goes below zero (that is, if {@code release} is called 1623 * a greater number of times than {@link #acquire}), an exception is thrown. 1624 * 1625 * If this WifiLock is not reference-counted, the first call to {@code release} (after 1626 * the radio was locked using {@link #acquire}) will unlock the radio, and subsequent 1627 * calls will be ignored. 1628 */ 1629 public void release() { 1630 synchronized (mBinder) { 1631 if (mRefCounted ? (--mRefCount == 0) : (mHeld)) { 1632 try { 1633 mService.releaseWifiLock(mBinder); 1634 synchronized (WifiManager.this) { 1635 mActiveLockCount--; 1636 } 1637 } catch (RemoteException ignore) { 1638 } 1639 mHeld = false; 1640 } 1641 if (mRefCount < 0) { 1642 throw new RuntimeException("WifiLock under-locked " + mTag); 1643 } 1644 } 1645 } 1646 1647 /** 1648 * Controls whether this is a reference-counted or non-reference-counted WifiLock. 1649 * 1650 * Reference-counted WifiLocks keep track of the number of calls to {@link #acquire} and 1651 * {@link #release}, and only allow the radio to sleep when every call to {@link #acquire} 1652 * has been balanced with a call to {@link #release}. Non-reference-counted WifiLocks 1653 * lock the radio whenever {@link #acquire} is called and it is unlocked, and unlock the 1654 * radio whenever {@link #release} is called and it is locked. 1655 * 1656 * @param refCounted true if this WifiLock should keep a reference count 1657 */ 1658 public void setReferenceCounted(boolean refCounted) { 1659 mRefCounted = refCounted; 1660 } 1661 1662 /** 1663 * Checks whether this WifiLock is currently held. 1664 * 1665 * @return true if this WifiLock is held, false otherwise 1666 */ 1667 public boolean isHeld() { 1668 synchronized (mBinder) { 1669 return mHeld; 1670 } 1671 } 1672 1673 public void setWorkSource(WorkSource ws) { 1674 synchronized (mBinder) { 1675 if (ws != null && ws.size() == 0) { 1676 ws = null; 1677 } 1678 boolean changed = true; 1679 if (ws == null) { 1680 mWorkSource = null; 1681 } else if (mWorkSource == null) { 1682 changed = mWorkSource != null; 1683 mWorkSource = new WorkSource(ws); 1684 } else { 1685 changed = mWorkSource.diff(ws); 1686 if (changed) { 1687 mWorkSource.set(ws); 1688 } 1689 } 1690 if (changed && mHeld) { 1691 try { 1692 mService.updateWifiLockWorkSource(mBinder, mWorkSource); 1693 } catch (RemoteException e) { 1694 } 1695 } 1696 } 1697 } 1698 1699 public String toString() { 1700 String s1, s2, s3; 1701 synchronized (mBinder) { 1702 s1 = Integer.toHexString(System.identityHashCode(this)); 1703 s2 = mHeld ? "held; " : ""; 1704 if (mRefCounted) { 1705 s3 = "refcounted: refcount = " + mRefCount; 1706 } else { 1707 s3 = "not refcounted"; 1708 } 1709 return "WifiLock{ " + s1 + "; " + s2 + s3 + " }"; 1710 } 1711 } 1712 1713 @Override 1714 protected void finalize() throws Throwable { 1715 super.finalize(); 1716 synchronized (mBinder) { 1717 if (mHeld) { 1718 try { 1719 mService.releaseWifiLock(mBinder); 1720 synchronized (WifiManager.this) { 1721 mActiveLockCount--; 1722 } 1723 } catch (RemoteException ignore) { 1724 } 1725 } 1726 } 1727 } 1728 } 1729 1730 /** 1731 * Creates a new WifiLock. 1732 * 1733 * @param lockType the type of lock to create. See {@link #WIFI_MODE_FULL}, 1734 * {@link #WIFI_MODE_FULL_HIGH_PERF} and {@link #WIFI_MODE_SCAN_ONLY} for 1735 * descriptions of the types of Wi-Fi locks. 1736 * @param tag a tag for the WifiLock to identify it in debugging messages. This string is 1737 * never shown to the user under normal conditions, but should be descriptive 1738 * enough to identify your application and the specific WifiLock within it, if it 1739 * holds multiple WifiLocks. 1740 * 1741 * @return a new, unacquired WifiLock with the given tag. 1742 * 1743 * @see WifiLock 1744 */ 1745 public WifiLock createWifiLock(int lockType, String tag) { 1746 return new WifiLock(lockType, tag); 1747 } 1748 1749 /** 1750 * Creates a new WifiLock. 1751 * 1752 * @param tag a tag for the WifiLock to identify it in debugging messages. This string is 1753 * never shown to the user under normal conditions, but should be descriptive 1754 * enough to identify your application and the specific WifiLock within it, if it 1755 * holds multiple WifiLocks. 1756 * 1757 * @return a new, unacquired WifiLock with the given tag. 1758 * 1759 * @see WifiLock 1760 */ 1761 public WifiLock createWifiLock(String tag) { 1762 return new WifiLock(WIFI_MODE_FULL, tag); 1763 } 1764 1765 1766 /** 1767 * Create a new MulticastLock 1768 * 1769 * @param tag a tag for the MulticastLock to identify it in debugging 1770 * messages. This string is never shown to the user under 1771 * normal conditions, but should be descriptive enough to 1772 * identify your application and the specific MulticastLock 1773 * within it, if it holds multiple MulticastLocks. 1774 * 1775 * @return a new, unacquired MulticastLock with the given tag. 1776 * 1777 * @see MulticastLock 1778 */ 1779 public MulticastLock createMulticastLock(String tag) { 1780 return new MulticastLock(tag); 1781 } 1782 1783 /** 1784 * Allows an application to receive Wifi Multicast packets. 1785 * Normally the Wifi stack filters out packets not explicitly 1786 * addressed to this device. Acquring a MulticastLock will 1787 * cause the stack to receive packets addressed to multicast 1788 * addresses. Processing these extra packets can cause a noticable 1789 * battery drain and should be disabled when not needed. 1790 */ 1791 public class MulticastLock { 1792 private String mTag; 1793 private final IBinder mBinder; 1794 private int mRefCount; 1795 private boolean mRefCounted; 1796 private boolean mHeld; 1797 1798 private MulticastLock(String tag) { 1799 mTag = tag; 1800 mBinder = new Binder(); 1801 mRefCount = 0; 1802 mRefCounted = true; 1803 mHeld = false; 1804 } 1805 1806 /** 1807 * Locks Wifi Multicast on until {@link #release} is called. 1808 * 1809 * If this MulticastLock is reference-counted each call to 1810 * {@code acquire} will increment the reference count, and the 1811 * wifi interface will receive multicast packets as long as the 1812 * reference count is above zero. 1813 * 1814 * If this MulticastLock is not reference-counted, the first call to 1815 * {@code acquire} will turn on the multicast packets, but subsequent 1816 * calls will be ignored. Only one call to {@link #release} will 1817 * be required, regardless of the number of times that {@code acquire} 1818 * is called. 1819 * 1820 * Note that other applications may also lock Wifi Multicast on. 1821 * Only they can relinquish their lock. 1822 * 1823 * Also note that applications cannot leave Multicast locked on. 1824 * When an app exits or crashes, any Multicast locks will be released. 1825 */ 1826 public void acquire() { 1827 synchronized (mBinder) { 1828 if (mRefCounted ? (++mRefCount == 1) : (!mHeld)) { 1829 try { 1830 mService.acquireMulticastLock(mBinder, mTag); 1831 synchronized (WifiManager.this) { 1832 if (mActiveLockCount >= MAX_ACTIVE_LOCKS) { 1833 mService.releaseMulticastLock(); 1834 throw new UnsupportedOperationException( 1835 "Exceeded maximum number of wifi locks"); 1836 } 1837 mActiveLockCount++; 1838 } 1839 } catch (RemoteException ignore) { 1840 } 1841 mHeld = true; 1842 } 1843 } 1844 } 1845 1846 /** 1847 * Unlocks Wifi Multicast, restoring the filter of packets 1848 * not addressed specifically to this device and saving power. 1849 * 1850 * If this MulticastLock is reference-counted, each call to 1851 * {@code release} will decrement the reference count, and the 1852 * multicast packets will only stop being received when the reference 1853 * count reaches zero. If the reference count goes below zero (that 1854 * is, if {@code release} is called a greater number of times than 1855 * {@link #acquire}), an exception is thrown. 1856 * 1857 * If this MulticastLock is not reference-counted, the first call to 1858 * {@code release} (after the radio was multicast locked using 1859 * {@link #acquire}) will unlock the multicast, and subsequent calls 1860 * will be ignored. 1861 * 1862 * Note that if any other Wifi Multicast Locks are still outstanding 1863 * this {@code release} call will not have an immediate effect. Only 1864 * when all applications have released all their Multicast Locks will 1865 * the Multicast filter be turned back on. 1866 * 1867 * Also note that when an app exits or crashes all of its Multicast 1868 * Locks will be automatically released. 1869 */ 1870 public void release() { 1871 synchronized (mBinder) { 1872 if (mRefCounted ? (--mRefCount == 0) : (mHeld)) { 1873 try { 1874 mService.releaseMulticastLock(); 1875 synchronized (WifiManager.this) { 1876 mActiveLockCount--; 1877 } 1878 } catch (RemoteException ignore) { 1879 } 1880 mHeld = false; 1881 } 1882 if (mRefCount < 0) { 1883 throw new RuntimeException("MulticastLock under-locked " 1884 + mTag); 1885 } 1886 } 1887 } 1888 1889 /** 1890 * Controls whether this is a reference-counted or non-reference- 1891 * counted MulticastLock. 1892 * 1893 * Reference-counted MulticastLocks keep track of the number of calls 1894 * to {@link #acquire} and {@link #release}, and only stop the 1895 * reception of multicast packets when every call to {@link #acquire} 1896 * has been balanced with a call to {@link #release}. Non-reference- 1897 * counted MulticastLocks allow the reception of multicast packets 1898 * whenever {@link #acquire} is called and stop accepting multicast 1899 * packets whenever {@link #release} is called. 1900 * 1901 * @param refCounted true if this MulticastLock should keep a reference 1902 * count 1903 */ 1904 public void setReferenceCounted(boolean refCounted) { 1905 mRefCounted = refCounted; 1906 } 1907 1908 /** 1909 * Checks whether this MulticastLock is currently held. 1910 * 1911 * @return true if this MulticastLock is held, false otherwise 1912 */ 1913 public boolean isHeld() { 1914 synchronized (mBinder) { 1915 return mHeld; 1916 } 1917 } 1918 1919 public String toString() { 1920 String s1, s2, s3; 1921 synchronized (mBinder) { 1922 s1 = Integer.toHexString(System.identityHashCode(this)); 1923 s2 = mHeld ? "held; " : ""; 1924 if (mRefCounted) { 1925 s3 = "refcounted: refcount = " + mRefCount; 1926 } else { 1927 s3 = "not refcounted"; 1928 } 1929 return "MulticastLock{ " + s1 + "; " + s2 + s3 + " }"; 1930 } 1931 } 1932 1933 @Override 1934 protected void finalize() throws Throwable { 1935 super.finalize(); 1936 setReferenceCounted(false); 1937 release(); 1938 } 1939 } 1940 1941 /** 1942 * Check multicast filter status. 1943 * 1944 * @return true if multicast packets are allowed. 1945 * 1946 * @hide pending API council approval 1947 */ 1948 public boolean isMulticastEnabled() { 1949 try { 1950 return mService.isMulticastEnabled(); 1951 } catch (RemoteException e) { 1952 return false; 1953 } 1954 } 1955 1956 /** 1957 * Initialize the multicast filtering to 'on' 1958 * @hide no intent to publish 1959 */ 1960 public boolean initializeMulticastFiltering() { 1961 try { 1962 mService.initializeMulticastFiltering(); 1963 return true; 1964 } catch (RemoteException e) { 1965 return false; 1966 } 1967 } 1968} 1969