WifiManager.java revision 88759bbd31e05a4163e1f8e72804ca83000afd53
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 * Calculates the level of the signal. This should be used any time a signal 910 * is being shown. 911 * 912 * @param rssi The power of the signal measured in RSSI. 913 * @param numLevels The number of levels to consider in the calculated 914 * level. 915 * @return A level of the signal, given in the range of 0 to numLevels-1 916 * (both inclusive). 917 */ 918 public static int calculateSignalLevel(int rssi, int numLevels) { 919 if (rssi <= MIN_RSSI) { 920 return 0; 921 } else if (rssi >= MAX_RSSI) { 922 return numLevels - 1; 923 } else { 924 float inputRange = (MAX_RSSI - MIN_RSSI); 925 float outputRange = (numLevels - 1); 926 return (int)((float)(rssi - MIN_RSSI) * outputRange / inputRange); 927 } 928 } 929 930 /** 931 * Compares two signal strengths. 932 * 933 * @param rssiA The power of the first signal measured in RSSI. 934 * @param rssiB The power of the second signal measured in RSSI. 935 * @return Returns <0 if the first signal is weaker than the second signal, 936 * 0 if the two signals have the same strength, and >0 if the first 937 * signal is stronger than the second signal. 938 */ 939 public static int compareSignalLevel(int rssiA, int rssiB) { 940 return rssiA - rssiB; 941 } 942 943 /** 944 * Start AccessPoint mode with the specified 945 * configuration. If the radio is already running in 946 * AP mode, update the new configuration 947 * Note that starting in access point mode disables station 948 * mode operation 949 * @param wifiConfig SSID, security and channel details as 950 * part of WifiConfiguration 951 * @return {@code true} if the operation succeeds, {@code false} otherwise 952 * 953 * @hide Dont open up yet 954 */ 955 public boolean setWifiApEnabled(WifiConfiguration wifiConfig, boolean enabled) { 956 try { 957 mService.setWifiApEnabled(wifiConfig, enabled); 958 return true; 959 } catch (RemoteException e) { 960 return false; 961 } 962 } 963 964 /** 965 * Gets the Wi-Fi enabled state. 966 * @return One of {@link #WIFI_AP_STATE_DISABLED}, 967 * {@link #WIFI_AP_STATE_DISABLING}, {@link #WIFI_AP_STATE_ENABLED}, 968 * {@link #WIFI_AP_STATE_ENABLING}, {@link #WIFI_AP_STATE_FAILED} 969 * @see #isWifiApEnabled() 970 * 971 * @hide Dont open yet 972 */ 973 public int getWifiApState() { 974 try { 975 return mService.getWifiApEnabledState(); 976 } catch (RemoteException e) { 977 return WIFI_AP_STATE_FAILED; 978 } 979 } 980 981 /** 982 * Return whether Wi-Fi AP is enabled or disabled. 983 * @return {@code true} if Wi-Fi AP is enabled 984 * @see #getWifiApState() 985 * 986 * @hide Dont open yet 987 */ 988 public boolean isWifiApEnabled() { 989 return getWifiApState() == WIFI_AP_STATE_ENABLED; 990 } 991 992 /** 993 * Gets the Wi-Fi AP Configuration. 994 * @return AP details in WifiConfiguration 995 * 996 * @hide Dont open yet 997 */ 998 public WifiConfiguration getWifiApConfiguration() { 999 try { 1000 return mService.getWifiApConfiguration(); 1001 } catch (RemoteException e) { 1002 return null; 1003 } 1004 } 1005 1006 /** 1007 * Sets the Wi-Fi AP Configuration. 1008 * @return {@code true} if the operation succeeded, {@code false} otherwise 1009 * 1010 * @hide Dont open yet 1011 */ 1012 public boolean setWifiApConfiguration(WifiConfiguration wifiConfig) { 1013 try { 1014 mService.setWifiApConfiguration(wifiConfig); 1015 return true; 1016 } catch (RemoteException e) { 1017 return false; 1018 } 1019 } 1020 1021 /** 1022 * Start the driver and connect to network. 1023 * 1024 * This function will over-ride WifiLock and device idle status. For example, 1025 * even if the device is idle or there is only a scan-only lock held, 1026 * a start wifi would mean that wifi connection is kept active until 1027 * a stopWifi() is sent. 1028 * 1029 * This API is used by WifiStateTracker 1030 * 1031 * @return {@code true} if the operation succeeds else {@code false} 1032 * @hide 1033 */ 1034 public boolean startWifi() { 1035 try { 1036 mService.startWifi(); 1037 return true; 1038 } catch (RemoteException e) { 1039 return false; 1040 } 1041 } 1042 1043 /** 1044 * Disconnect from a network (if any) and stop the driver. 1045 * 1046 * This function will over-ride WifiLock and device idle status. Wi-Fi 1047 * stays inactive until a startWifi() is issued. 1048 * 1049 * This API is used by WifiStateTracker 1050 * 1051 * @return {@code true} if the operation succeeds else {@code false} 1052 * @hide 1053 */ 1054 public boolean stopWifi() { 1055 try { 1056 mService.stopWifi(); 1057 return true; 1058 } catch (RemoteException e) { 1059 return false; 1060 } 1061 } 1062 1063 /** 1064 * Add a bssid to the supplicant blacklist 1065 * 1066 * This API is used by WifiWatchdogService 1067 * 1068 * @return {@code true} if the operation succeeds else {@code false} 1069 * @hide 1070 */ 1071 public boolean addToBlacklist(String bssid) { 1072 try { 1073 mService.addToBlacklist(bssid); 1074 return true; 1075 } catch (RemoteException e) { 1076 return false; 1077 } 1078 } 1079 1080 /** 1081 * Clear the supplicant blacklist 1082 * 1083 * This API is used by WifiWatchdogService 1084 * 1085 * @return {@code true} if the operation succeeds else {@code false} 1086 * @hide 1087 */ 1088 public boolean clearBlacklist() { 1089 try { 1090 mService.clearBlacklist(); 1091 return true; 1092 } catch (RemoteException e) { 1093 return false; 1094 } 1095 } 1096 1097 /* TODO: deprecate synchronous API and open up the following API */ 1098 1099 private static final int BASE = Protocol.BASE_WIFI_MANAGER; 1100 1101 /* Commands to WifiService */ 1102 /** @hide */ 1103 public static final int CONNECT_NETWORK = BASE + 1; 1104 /** @hide */ 1105 public static final int CONNECT_NETWORK_FAILED = BASE + 2; 1106 /** @hide */ 1107 public static final int CONNECT_NETWORK_SUCCEEDED = BASE + 3; 1108 1109 /** @hide */ 1110 public static final int FORGET_NETWORK = BASE + 4; 1111 /** @hide */ 1112 public static final int FORGET_NETWORK_FAILED = BASE + 5; 1113 /** @hide */ 1114 public static final int FORGET_NETWORK_SUCCEEDED = BASE + 6; 1115 1116 /** @hide */ 1117 public static final int SAVE_NETWORK = BASE + 7; 1118 /** @hide */ 1119 public static final int SAVE_NETWORK_FAILED = BASE + 8; 1120 /** @hide */ 1121 public static final int SAVE_NETWORK_SUCCEEDED = BASE + 9; 1122 1123 /** @hide */ 1124 public static final int START_WPS = BASE + 10; 1125 /** @hide */ 1126 public static final int START_WPS_SUCCEEDED = BASE + 11; 1127 /** @hide */ 1128 public static final int WPS_FAILED = BASE + 12; 1129 /** @hide */ 1130 public static final int WPS_COMPLETED = BASE + 13; 1131 1132 /** @hide */ 1133 public static final int CANCEL_WPS = BASE + 14; 1134 /** @hide */ 1135 public static final int CANCEL_WPS_FAILED = BASE + 15; 1136 /** @hide */ 1137 public static final int CANCEL_WPS_SUCCEDED = BASE + 16; 1138 1139 /** @hide */ 1140 public static final int DISABLE_NETWORK = BASE + 17; 1141 /** @hide */ 1142 public static final int DISABLE_NETWORK_FAILED = BASE + 18; 1143 /** @hide */ 1144 public static final int DISABLE_NETWORK_SUCCEEDED = BASE + 19; 1145 1146 /* For system use only */ 1147 /** @hide */ 1148 public static final int ENABLE_TRAFFIC_STATS_POLL = BASE + 21; 1149 /** @hide */ 1150 public static final int TRAFFIC_STATS_POLL = BASE + 22; 1151 1152 1153 /** 1154 * Passed with {@link ActionListener#onFailure}. 1155 * Indicates that the operation failed due to an internal error. 1156 * @hide 1157 */ 1158 public static final int ERROR = 0; 1159 1160 /** 1161 * Passed with {@link ActionListener#onFailure}. 1162 * Indicates that the operation is already in progress 1163 * @hide 1164 */ 1165 public static final int IN_PROGRESS = 1; 1166 1167 /** 1168 * Passed with {@link ActionListener#onFailure}. 1169 * Indicates that the operation failed because the framework is busy and 1170 * unable to service the request 1171 * @hide 1172 */ 1173 public static final int BUSY = 2; 1174 1175 /* WPS specific errors */ 1176 /** WPS overlap detected {@hide} */ 1177 public static final int WPS_OVERLAP_ERROR = 3; 1178 /** WEP on WPS is prohibited {@hide} */ 1179 public static final int WPS_WEP_PROHIBITED = 4; 1180 /** TKIP only prohibited {@hide} */ 1181 public static final int WPS_TKIP_ONLY_PROHIBITED = 5; 1182 /** Authentication failure on WPS {@hide} */ 1183 public static final int WPS_AUTH_FAILURE = 6; 1184 /** WPS timed out {@hide} */ 1185 public static final int WPS_TIMED_OUT = 7; 1186 1187 /** Interface for callback invocation on an application action {@hide} */ 1188 public interface ActionListener { 1189 /** The operation succeeded */ 1190 public void onSuccess(); 1191 /** 1192 * The operation failed 1193 * @param reason The reason for failure could be one of 1194 * {@link #ERROR}, {@link #IN_PROGRESS} or {@link #BUSY} 1195 */ 1196 public void onFailure(int reason); 1197 } 1198 1199 /** Interface for callback invocation on a start WPS action {@hide} */ 1200 public interface WpsListener { 1201 /** WPS start succeeded */ 1202 public void onStartSuccess(String pin); 1203 1204 /** WPS operation completed succesfully */ 1205 public void onCompletion(); 1206 1207 /** 1208 * WPS operation failed 1209 * @param reason The reason for failure could be one of 1210 * {@link #IN_PROGRESS}, {@link #WPS_OVERLAP_ERROR},{@link #ERROR} or {@link #BUSY} 1211 */ 1212 public void onFailure(int reason); 1213 } 1214 1215 private class ServiceHandler extends Handler { 1216 ServiceHandler(Looper looper) { 1217 super(looper); 1218 } 1219 1220 @Override 1221 public void handleMessage(Message message) { 1222 Object listener = removeListener(message.arg2); 1223 switch (message.what) { 1224 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: 1225 if (message.arg1 == AsyncChannel.STATUS_SUCCESSFUL) { 1226 mAsyncChannel.sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION); 1227 } else { 1228 Log.e(TAG, "Failed to set up channel connection"); 1229 // This will cause all further async API calls on the WifiManager 1230 // to fail and throw an exception 1231 mAsyncChannel = null; 1232 } 1233 mConnected.countDown(); 1234 break; 1235 case AsyncChannel.CMD_CHANNEL_FULLY_CONNECTED: 1236 // Ignore 1237 break; 1238 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: 1239 Log.e(TAG, "Channel connection lost"); 1240 // This will cause all further async API calls on the WifiManager 1241 // to fail and throw an exception 1242 mAsyncChannel = null; 1243 break; 1244 /* ActionListeners grouped together */ 1245 case WifiManager.CONNECT_NETWORK_FAILED: 1246 case WifiManager.FORGET_NETWORK_FAILED: 1247 case WifiManager.SAVE_NETWORK_FAILED: 1248 case WifiManager.CANCEL_WPS_FAILED: 1249 case WifiManager.DISABLE_NETWORK_FAILED: 1250 if (listener != null) { 1251 ((ActionListener) listener).onFailure(message.arg1); 1252 } 1253 break; 1254 /* ActionListeners grouped together */ 1255 case WifiManager.CONNECT_NETWORK_SUCCEEDED: 1256 case WifiManager.FORGET_NETWORK_SUCCEEDED: 1257 case WifiManager.SAVE_NETWORK_SUCCEEDED: 1258 case WifiManager.CANCEL_WPS_SUCCEDED: 1259 case WifiManager.DISABLE_NETWORK_SUCCEEDED: 1260 if (listener != null) { 1261 ((ActionListener) listener).onSuccess(); 1262 } 1263 break; 1264 case WifiManager.START_WPS_SUCCEEDED: 1265 if (listener != null) { 1266 WpsResult result = (WpsResult) message.obj; 1267 ((WpsListener) listener).onStartSuccess(result.pin); 1268 //Listener needs to stay until completion or failure 1269 synchronized(mListenerMapLock) { 1270 mListenerMap.put(message.arg2, listener); 1271 } 1272 } 1273 break; 1274 case WifiManager.WPS_COMPLETED: 1275 if (listener != null) { 1276 ((WpsListener) listener).onCompletion(); 1277 } 1278 break; 1279 case WifiManager.WPS_FAILED: 1280 if (listener != null) { 1281 ((WpsListener) listener).onFailure(message.arg1); 1282 } 1283 break; 1284 default: 1285 //ignore 1286 break; 1287 } 1288 } 1289 } 1290 1291 private int putListener(Object listener) { 1292 if (listener == null) return INVALID_KEY; 1293 int key; 1294 synchronized (mListenerMapLock) { 1295 do { 1296 key = mListenerKey++; 1297 } while (key == INVALID_KEY); 1298 mListenerMap.put(key, listener); 1299 } 1300 return key; 1301 } 1302 1303 private Object removeListener(int key) { 1304 if (key == INVALID_KEY) return null; 1305 synchronized (mListenerMapLock) { 1306 Object listener = mListenerMap.get(key); 1307 mListenerMap.remove(key); 1308 return listener; 1309 } 1310 } 1311 1312 private void init() { 1313 mWifiServiceMessenger = getWifiServiceMessenger(); 1314 if (mWifiServiceMessenger == null) throw new RuntimeException("Failed to initialize"); 1315 HandlerThread t = new HandlerThread("WifiManager"); 1316 t.start(); 1317 mHandler = new ServiceHandler(t.getLooper()); 1318 mAsyncChannel.connect(mContext, mHandler, mWifiServiceMessenger); 1319 try { 1320 mConnected.await(); 1321 } catch (InterruptedException e) { 1322 Log.e(TAG, "interrupted wait at init"); 1323 } 1324 } 1325 1326 private void validateChannel() { 1327 if (mAsyncChannel == null) throw new IllegalStateException( 1328 "Bad WifiManager instance state, re-initialize"); 1329 } 1330 1331 /** 1332 * Connect to a network with the given configuration. The network also 1333 * gets added to the supplicant configuration. 1334 * 1335 * For a new network, this function is used instead of a 1336 * sequence of addNetwork(), enableNetwork(), saveConfiguration() and 1337 * reconnect() 1338 * 1339 * @param config the set of variables that describe the configuration, 1340 * contained in a {@link WifiConfiguration} object. 1341 * @param listener for callbacks on success or failure. Can be null. 1342 * @throws IllegalStateException if the WifiManager instance needs to be 1343 * initialized again 1344 * 1345 * @hide 1346 */ 1347 public void connect(WifiConfiguration config, ActionListener listener) { 1348 if (config == null) throw new IllegalArgumentException("config cannot be null"); 1349 validateChannel(); 1350 // Use INVALID_NETWORK_ID for arg1 when passing a config object 1351 // arg1 is used to pass network id when the network already exists 1352 mAsyncChannel.sendMessage(CONNECT_NETWORK, WifiConfiguration.INVALID_NETWORK_ID, 1353 putListener(listener), config); 1354 } 1355 1356 /** 1357 * Connect to a network with the given networkId. 1358 * 1359 * This function is used instead of a enableNetwork(), saveConfiguration() and 1360 * reconnect() 1361 * 1362 * @param networkId the network id identifiying the network in the 1363 * supplicant configuration list 1364 * @param listener for callbacks on success or failure. Can be null. 1365 * @throws IllegalStateException if the WifiManager instance needs to be 1366 * initialized again 1367 * @hide 1368 */ 1369 public void connect(int networkId, ActionListener listener) { 1370 if (networkId < 0) throw new IllegalArgumentException("Network id cannot be negative"); 1371 validateChannel(); 1372 mAsyncChannel.sendMessage(CONNECT_NETWORK, networkId, putListener(listener)); 1373 } 1374 1375 /** 1376 * Save the given network in the supplicant config. If the network already 1377 * exists, the configuration is updated. A new network is enabled 1378 * by default. 1379 * 1380 * For a new network, this function is used instead of a 1381 * sequence of addNetwork(), enableNetwork() and saveConfiguration(). 1382 * 1383 * For an existing network, it accomplishes the task of updateNetwork() 1384 * and saveConfiguration() 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 * @hide 1392 */ 1393 public void save(WifiConfiguration config, ActionListener listener) { 1394 if (config == null) throw new IllegalArgumentException("config cannot be null"); 1395 validateChannel(); 1396 mAsyncChannel.sendMessage(SAVE_NETWORK, 0, putListener(listener), config); 1397 } 1398 1399 /** 1400 * Delete the network in the supplicant config. 1401 * 1402 * This function is used instead of a sequence of removeNetwork() 1403 * and saveConfiguration(). 1404 * 1405 * @param config the set of variables that describe the configuration, 1406 * contained in a {@link WifiConfiguration} object. 1407 * @param listener for callbacks on success or failure. Can be null. 1408 * @throws IllegalStateException if the WifiManager instance needs to be 1409 * initialized again 1410 * @hide 1411 */ 1412 public void forget(int netId, ActionListener listener) { 1413 if (netId < 0) throw new IllegalArgumentException("Network id cannot be negative"); 1414 validateChannel(); 1415 mAsyncChannel.sendMessage(FORGET_NETWORK, netId, putListener(listener)); 1416 } 1417 1418 /** 1419 * Disable network 1420 * 1421 * @param netId is the network Id 1422 * @param listener for callbacks on success or failure. Can be null. 1423 * @throws IllegalStateException if the WifiManager instance needs to be 1424 * initialized again 1425 * @hide 1426 */ 1427 public void disable(int netId, ActionListener listener) { 1428 if (netId < 0) throw new IllegalArgumentException("Network id cannot be negative"); 1429 validateChannel(); 1430 mAsyncChannel.sendMessage(DISABLE_NETWORK, netId, putListener(listener)); 1431 } 1432 1433 /** 1434 * Start Wi-fi Protected Setup 1435 * 1436 * @param config WPS configuration 1437 * @param listener for callbacks on success or failure. Can be null. 1438 * @throws IllegalStateException if the WifiManager instance needs to be 1439 * initialized again 1440 * @hide 1441 */ 1442 public void startWps(WpsInfo config, WpsListener listener) { 1443 if (config == null) throw new IllegalArgumentException("config cannot be null"); 1444 validateChannel(); 1445 mAsyncChannel.sendMessage(START_WPS, 0, putListener(listener), config); 1446 } 1447 1448 /** 1449 * Cancel any ongoing Wi-fi Protected Setup 1450 * 1451 * @param listener for callbacks on success or failure. Can be null. 1452 * @throws IllegalStateException if the WifiManager instance needs to be 1453 * initialized again 1454 * @hide 1455 */ 1456 public void cancelWps(ActionListener listener) { 1457 validateChannel(); 1458 mAsyncChannel.sendMessage(CANCEL_WPS, 0, putListener(listener)); 1459 } 1460 1461 /** 1462 * Get a reference to WifiService handler. This is used by a client to establish 1463 * an AsyncChannel communication with WifiService 1464 * 1465 * @return Messenger pointing to the WifiService handler 1466 * @hide 1467 */ 1468 public Messenger getWifiServiceMessenger() { 1469 try { 1470 return mService.getWifiServiceMessenger(); 1471 } catch (RemoteException e) { 1472 return null; 1473 } 1474 } 1475 1476 /** 1477 * Get a reference to WifiStateMachine handler. 1478 * @return Messenger pointing to the WifiService handler 1479 * @hide 1480 */ 1481 public Messenger getWifiStateMachineMessenger() { 1482 try { 1483 return mService.getWifiStateMachineMessenger(); 1484 } catch (RemoteException e) { 1485 return null; 1486 } 1487 } 1488 1489 /** 1490 * Returns the file in which IP and proxy configuration data is stored 1491 * @hide 1492 */ 1493 public String getConfigFile() { 1494 try { 1495 return mService.getConfigFile(); 1496 } catch (RemoteException e) { 1497 return null; 1498 } 1499 } 1500 1501 /** 1502 * Allows an application to keep the Wi-Fi radio awake. 1503 * Normally the Wi-Fi radio may turn off when the user has not used the device in a while. 1504 * Acquiring a WifiLock will keep the radio on until the lock is released. Multiple 1505 * applications may hold WifiLocks, and the radio will only be allowed to turn off when no 1506 * WifiLocks are held in any application. 1507 * <p> 1508 * Before using a WifiLock, consider carefully if your application requires Wi-Fi access, or 1509 * could function over a mobile network, if available. A program that needs to download large 1510 * files should hold a WifiLock to ensure that the download will complete, but a program whose 1511 * network usage is occasional or low-bandwidth should not hold a WifiLock to avoid adversely 1512 * affecting battery life. 1513 * <p> 1514 * Note that WifiLocks cannot override the user-level "Wi-Fi Enabled" setting, nor Airplane 1515 * Mode. They simply keep the radio from turning off when Wi-Fi is already on but the device 1516 * is idle. 1517 * <p> 1518 * Any application using a WifiLock must request the {@code android.permission.WAKE_LOCK} 1519 * permission in an {@code <uses-permission>} element of the application's manifest. 1520 */ 1521 public class WifiLock { 1522 private String mTag; 1523 private final IBinder mBinder; 1524 private int mRefCount; 1525 int mLockType; 1526 private boolean mRefCounted; 1527 private boolean mHeld; 1528 private WorkSource mWorkSource; 1529 1530 private WifiLock(int lockType, String tag) { 1531 mTag = tag; 1532 mLockType = lockType; 1533 mBinder = new Binder(); 1534 mRefCount = 0; 1535 mRefCounted = true; 1536 mHeld = false; 1537 } 1538 1539 /** 1540 * Locks the Wi-Fi radio on until {@link #release} is called. 1541 * 1542 * If this WifiLock is reference-counted, each call to {@code acquire} will increment the 1543 * reference count, and the radio will remain locked as long as the reference count is 1544 * above zero. 1545 * 1546 * If this WifiLock is not reference-counted, the first call to {@code acquire} will lock 1547 * the radio, but subsequent calls will be ignored. Only one call to {@link #release} 1548 * will be required, regardless of the number of times that {@code acquire} is called. 1549 */ 1550 public void acquire() { 1551 synchronized (mBinder) { 1552 if (mRefCounted ? (++mRefCount == 1) : (!mHeld)) { 1553 try { 1554 mService.acquireWifiLock(mBinder, mLockType, mTag, mWorkSource); 1555 synchronized (WifiManager.this) { 1556 if (mActiveLockCount >= MAX_ACTIVE_LOCKS) { 1557 mService.releaseWifiLock(mBinder); 1558 throw new UnsupportedOperationException( 1559 "Exceeded maximum number of wifi locks"); 1560 } 1561 mActiveLockCount++; 1562 } 1563 } catch (RemoteException ignore) { 1564 } 1565 mHeld = true; 1566 } 1567 } 1568 } 1569 1570 /** 1571 * Unlocks the Wi-Fi radio, allowing it to turn off when the device is idle. 1572 * 1573 * If this WifiLock is reference-counted, each call to {@code release} will decrement the 1574 * reference count, and the radio will be unlocked only when the reference count reaches 1575 * zero. If the reference count goes below zero (that is, if {@code release} is called 1576 * a greater number of times than {@link #acquire}), an exception is thrown. 1577 * 1578 * If this WifiLock is not reference-counted, the first call to {@code release} (after 1579 * the radio was locked using {@link #acquire}) will unlock the radio, and subsequent 1580 * calls will be ignored. 1581 */ 1582 public void release() { 1583 synchronized (mBinder) { 1584 if (mRefCounted ? (--mRefCount == 0) : (mHeld)) { 1585 try { 1586 mService.releaseWifiLock(mBinder); 1587 synchronized (WifiManager.this) { 1588 mActiveLockCount--; 1589 } 1590 } catch (RemoteException ignore) { 1591 } 1592 mHeld = false; 1593 } 1594 if (mRefCount < 0) { 1595 throw new RuntimeException("WifiLock under-locked " + mTag); 1596 } 1597 } 1598 } 1599 1600 /** 1601 * Controls whether this is a reference-counted or non-reference-counted WifiLock. 1602 * 1603 * Reference-counted WifiLocks keep track of the number of calls to {@link #acquire} and 1604 * {@link #release}, and only allow the radio to sleep when every call to {@link #acquire} 1605 * has been balanced with a call to {@link #release}. Non-reference-counted WifiLocks 1606 * lock the radio whenever {@link #acquire} is called and it is unlocked, and unlock the 1607 * radio whenever {@link #release} is called and it is locked. 1608 * 1609 * @param refCounted true if this WifiLock should keep a reference count 1610 */ 1611 public void setReferenceCounted(boolean refCounted) { 1612 mRefCounted = refCounted; 1613 } 1614 1615 /** 1616 * Checks whether this WifiLock is currently held. 1617 * 1618 * @return true if this WifiLock is held, false otherwise 1619 */ 1620 public boolean isHeld() { 1621 synchronized (mBinder) { 1622 return mHeld; 1623 } 1624 } 1625 1626 public void setWorkSource(WorkSource ws) { 1627 synchronized (mBinder) { 1628 if (ws != null && ws.size() == 0) { 1629 ws = null; 1630 } 1631 boolean changed = true; 1632 if (ws == null) { 1633 mWorkSource = null; 1634 } else if (mWorkSource == null) { 1635 changed = mWorkSource != null; 1636 mWorkSource = new WorkSource(ws); 1637 } else { 1638 changed = mWorkSource.diff(ws); 1639 if (changed) { 1640 mWorkSource.set(ws); 1641 } 1642 } 1643 if (changed && mHeld) { 1644 try { 1645 mService.updateWifiLockWorkSource(mBinder, mWorkSource); 1646 } catch (RemoteException e) { 1647 } 1648 } 1649 } 1650 } 1651 1652 public String toString() { 1653 String s1, s2, s3; 1654 synchronized (mBinder) { 1655 s1 = Integer.toHexString(System.identityHashCode(this)); 1656 s2 = mHeld ? "held; " : ""; 1657 if (mRefCounted) { 1658 s3 = "refcounted: refcount = " + mRefCount; 1659 } else { 1660 s3 = "not refcounted"; 1661 } 1662 return "WifiLock{ " + s1 + "; " + s2 + s3 + " }"; 1663 } 1664 } 1665 1666 @Override 1667 protected void finalize() throws Throwable { 1668 super.finalize(); 1669 synchronized (mBinder) { 1670 if (mHeld) { 1671 try { 1672 mService.releaseWifiLock(mBinder); 1673 synchronized (WifiManager.this) { 1674 mActiveLockCount--; 1675 } 1676 } catch (RemoteException ignore) { 1677 } 1678 } 1679 } 1680 } 1681 } 1682 1683 /** 1684 * Creates a new WifiLock. 1685 * 1686 * @param lockType the type of lock to create. See {@link #WIFI_MODE_FULL}, 1687 * {@link #WIFI_MODE_FULL_HIGH_PERF} and {@link #WIFI_MODE_SCAN_ONLY} for 1688 * descriptions of the types of Wi-Fi locks. 1689 * @param tag a tag for the WifiLock to identify it in debugging messages. This string is 1690 * never shown to the user under normal conditions, but should be descriptive 1691 * enough to identify your application and the specific WifiLock within it, if it 1692 * holds multiple WifiLocks. 1693 * 1694 * @return a new, unacquired WifiLock with the given tag. 1695 * 1696 * @see WifiLock 1697 */ 1698 public WifiLock createWifiLock(int lockType, String tag) { 1699 return new WifiLock(lockType, tag); 1700 } 1701 1702 /** 1703 * Creates a new WifiLock. 1704 * 1705 * @param tag a tag for the WifiLock to identify it in debugging messages. This string is 1706 * never shown to the user under normal conditions, but should be descriptive 1707 * enough to identify your application and the specific WifiLock within it, if it 1708 * holds multiple WifiLocks. 1709 * 1710 * @return a new, unacquired WifiLock with the given tag. 1711 * 1712 * @see WifiLock 1713 */ 1714 public WifiLock createWifiLock(String tag) { 1715 return new WifiLock(WIFI_MODE_FULL, tag); 1716 } 1717 1718 1719 /** 1720 * Create a new MulticastLock 1721 * 1722 * @param tag a tag for the MulticastLock to identify it in debugging 1723 * messages. This string is never shown to the user under 1724 * normal conditions, but should be descriptive enough to 1725 * identify your application and the specific MulticastLock 1726 * within it, if it holds multiple MulticastLocks. 1727 * 1728 * @return a new, unacquired MulticastLock with the given tag. 1729 * 1730 * @see MulticastLock 1731 */ 1732 public MulticastLock createMulticastLock(String tag) { 1733 return new MulticastLock(tag); 1734 } 1735 1736 /** 1737 * Allows an application to receive Wifi Multicast packets. 1738 * Normally the Wifi stack filters out packets not explicitly 1739 * addressed to this device. Acquring a MulticastLock will 1740 * cause the stack to receive packets addressed to multicast 1741 * addresses. Processing these extra packets can cause a noticable 1742 * battery drain and should be disabled when not needed. 1743 */ 1744 public class MulticastLock { 1745 private String mTag; 1746 private final IBinder mBinder; 1747 private int mRefCount; 1748 private boolean mRefCounted; 1749 private boolean mHeld; 1750 1751 private MulticastLock(String tag) { 1752 mTag = tag; 1753 mBinder = new Binder(); 1754 mRefCount = 0; 1755 mRefCounted = true; 1756 mHeld = false; 1757 } 1758 1759 /** 1760 * Locks Wifi Multicast on until {@link #release} is called. 1761 * 1762 * If this MulticastLock is reference-counted each call to 1763 * {@code acquire} will increment the reference count, and the 1764 * wifi interface will receive multicast packets as long as the 1765 * reference count is above zero. 1766 * 1767 * If this MulticastLock is not reference-counted, the first call to 1768 * {@code acquire} will turn on the multicast packets, but subsequent 1769 * calls will be ignored. Only one call to {@link #release} will 1770 * be required, regardless of the number of times that {@code acquire} 1771 * is called. 1772 * 1773 * Note that other applications may also lock Wifi Multicast on. 1774 * Only they can relinquish their lock. 1775 * 1776 * Also note that applications cannot leave Multicast locked on. 1777 * When an app exits or crashes, any Multicast locks will be released. 1778 */ 1779 public void acquire() { 1780 synchronized (mBinder) { 1781 if (mRefCounted ? (++mRefCount == 1) : (!mHeld)) { 1782 try { 1783 mService.acquireMulticastLock(mBinder, mTag); 1784 synchronized (WifiManager.this) { 1785 if (mActiveLockCount >= MAX_ACTIVE_LOCKS) { 1786 mService.releaseMulticastLock(); 1787 throw new UnsupportedOperationException( 1788 "Exceeded maximum number of wifi locks"); 1789 } 1790 mActiveLockCount++; 1791 } 1792 } catch (RemoteException ignore) { 1793 } 1794 mHeld = true; 1795 } 1796 } 1797 } 1798 1799 /** 1800 * Unlocks Wifi Multicast, restoring the filter of packets 1801 * not addressed specifically to this device and saving power. 1802 * 1803 * If this MulticastLock is reference-counted, each call to 1804 * {@code release} will decrement the reference count, and the 1805 * multicast packets will only stop being received when the reference 1806 * count reaches zero. If the reference count goes below zero (that 1807 * is, if {@code release} is called a greater number of times than 1808 * {@link #acquire}), an exception is thrown. 1809 * 1810 * If this MulticastLock is not reference-counted, the first call to 1811 * {@code release} (after the radio was multicast locked using 1812 * {@link #acquire}) will unlock the multicast, and subsequent calls 1813 * will be ignored. 1814 * 1815 * Note that if any other Wifi Multicast Locks are still outstanding 1816 * this {@code release} call will not have an immediate effect. Only 1817 * when all applications have released all their Multicast Locks will 1818 * the Multicast filter be turned back on. 1819 * 1820 * Also note that when an app exits or crashes all of its Multicast 1821 * Locks will be automatically released. 1822 */ 1823 public void release() { 1824 synchronized (mBinder) { 1825 if (mRefCounted ? (--mRefCount == 0) : (mHeld)) { 1826 try { 1827 mService.releaseMulticastLock(); 1828 synchronized (WifiManager.this) { 1829 mActiveLockCount--; 1830 } 1831 } catch (RemoteException ignore) { 1832 } 1833 mHeld = false; 1834 } 1835 if (mRefCount < 0) { 1836 throw new RuntimeException("MulticastLock under-locked " 1837 + mTag); 1838 } 1839 } 1840 } 1841 1842 /** 1843 * Controls whether this is a reference-counted or non-reference- 1844 * counted MulticastLock. 1845 * 1846 * Reference-counted MulticastLocks keep track of the number of calls 1847 * to {@link #acquire} and {@link #release}, and only stop the 1848 * reception of multicast packets when every call to {@link #acquire} 1849 * has been balanced with a call to {@link #release}. Non-reference- 1850 * counted MulticastLocks allow the reception of multicast packets 1851 * whenever {@link #acquire} is called and stop accepting multicast 1852 * packets whenever {@link #release} is called. 1853 * 1854 * @param refCounted true if this MulticastLock should keep a reference 1855 * count 1856 */ 1857 public void setReferenceCounted(boolean refCounted) { 1858 mRefCounted = refCounted; 1859 } 1860 1861 /** 1862 * Checks whether this MulticastLock is currently held. 1863 * 1864 * @return true if this MulticastLock is held, false otherwise 1865 */ 1866 public boolean isHeld() { 1867 synchronized (mBinder) { 1868 return mHeld; 1869 } 1870 } 1871 1872 public String toString() { 1873 String s1, s2, s3; 1874 synchronized (mBinder) { 1875 s1 = Integer.toHexString(System.identityHashCode(this)); 1876 s2 = mHeld ? "held; " : ""; 1877 if (mRefCounted) { 1878 s3 = "refcounted: refcount = " + mRefCount; 1879 } else { 1880 s3 = "not refcounted"; 1881 } 1882 return "MulticastLock{ " + s1 + "; " + s2 + s3 + " }"; 1883 } 1884 } 1885 1886 @Override 1887 protected void finalize() throws Throwable { 1888 super.finalize(); 1889 setReferenceCounted(false); 1890 release(); 1891 } 1892 } 1893 1894 /** 1895 * Check multicast filter status. 1896 * 1897 * @return true if multicast packets are allowed. 1898 * 1899 * @hide pending API council approval 1900 */ 1901 public boolean isMulticastEnabled() { 1902 try { 1903 return mService.isMulticastEnabled(); 1904 } catch (RemoteException e) { 1905 return false; 1906 } 1907 } 1908 1909 /** 1910 * Initialize the multicast filtering to 'on' 1911 * @hide no intent to publish 1912 */ 1913 public boolean initializeMulticastFiltering() { 1914 try { 1915 mService.initializeMulticastFiltering(); 1916 return true; 1917 } catch (RemoteException e) { 1918 return false; 1919 } 1920 } 1921} 1922