ConnectivityManager.java revision 9ac3dbe1ce68fba1af012112894d54c3024195f8
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 */ 16package android.net; 17 18import static com.android.internal.util.Preconditions.checkNotNull; 19 20import android.annotation.SdkConstant; 21import android.annotation.SdkConstant.SdkConstantType; 22import android.app.PendingIntent; 23import android.content.Context; 24import android.content.Intent; 25import android.os.Binder; 26import android.os.Build.VERSION_CODES; 27import android.os.Handler; 28import android.os.HandlerThread; 29import android.os.IBinder; 30import android.os.INetworkActivityListener; 31import android.os.INetworkManagementService; 32import android.os.Looper; 33import android.os.Message; 34import android.os.Messenger; 35import android.os.RemoteException; 36import android.os.ServiceManager; 37import android.provider.Settings; 38import android.telephony.TelephonyManager; 39import android.util.ArrayMap; 40import android.util.Log; 41 42import com.android.internal.telephony.ITelephony; 43import com.android.internal.telephony.PhoneConstants; 44import com.android.internal.util.Protocol; 45 46import java.net.InetAddress; 47import java.util.concurrent.atomic.AtomicInteger; 48import java.util.HashMap; 49 50/** 51 * Class that answers queries about the state of network connectivity. It also 52 * notifies applications when network connectivity changes. Get an instance 53 * of this class by calling 54 * {@link android.content.Context#getSystemService(String) Context.getSystemService(Context.CONNECTIVITY_SERVICE)}. 55 * <p> 56 * The primary responsibilities of this class are to: 57 * <ol> 58 * <li>Monitor network connections (Wi-Fi, GPRS, UMTS, etc.)</li> 59 * <li>Send broadcast intents when network connectivity changes</li> 60 * <li>Attempt to "fail over" to another network when connectivity to a network 61 * is lost</li> 62 * <li>Provide an API that allows applications to query the coarse-grained or fine-grained 63 * state of the available networks</li> 64 * <li>Provide an API that allows applications to request and select networks for their data 65 * traffic</li> 66 * </ol> 67 */ 68public class ConnectivityManager { 69 private static final String TAG = "ConnectivityManager"; 70 71 /** 72 * A change in network connectivity has occurred. A default connection has either 73 * been established or lost. The NetworkInfo for the affected network is 74 * sent as an extra; it should be consulted to see what kind of 75 * connectivity event occurred. 76 * <p/> 77 * If this is a connection that was the result of failing over from a 78 * disconnected network, then the FAILOVER_CONNECTION boolean extra is 79 * set to true. 80 * <p/> 81 * For a loss of connectivity, if the connectivity manager is attempting 82 * to connect (or has already connected) to another network, the 83 * NetworkInfo for the new network is also passed as an extra. This lets 84 * any receivers of the broadcast know that they should not necessarily 85 * tell the user that no data traffic will be possible. Instead, the 86 * receiver should expect another broadcast soon, indicating either that 87 * the failover attempt succeeded (and so there is still overall data 88 * connectivity), or that the failover attempt failed, meaning that all 89 * connectivity has been lost. 90 * <p/> 91 * For a disconnect event, the boolean extra EXTRA_NO_CONNECTIVITY 92 * is set to {@code true} if there are no connected networks at all. 93 */ 94 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) 95 public static final String CONNECTIVITY_ACTION = "android.net.conn.CONNECTIVITY_CHANGE"; 96 97 /** 98 * Identical to {@link #CONNECTIVITY_ACTION} broadcast, but sent without any 99 * applicable {@link Settings.Global#CONNECTIVITY_CHANGE_DELAY}. 100 * 101 * @hide 102 */ 103 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) 104 public static final String CONNECTIVITY_ACTION_IMMEDIATE = 105 "android.net.conn.CONNECTIVITY_CHANGE_IMMEDIATE"; 106 107 /** 108 * The lookup key for a {@link NetworkInfo} object. Retrieve with 109 * {@link android.content.Intent#getParcelableExtra(String)}. 110 * 111 * @deprecated Since {@link NetworkInfo} can vary based on UID, applications 112 * should always obtain network information through 113 * {@link #getActiveNetworkInfo()} or 114 * {@link #getAllNetworkInfo()}. 115 * @see #EXTRA_NETWORK_TYPE 116 */ 117 @Deprecated 118 public static final String EXTRA_NETWORK_INFO = "networkInfo"; 119 120 /** 121 * Network type which triggered a {@link #CONNECTIVITY_ACTION} broadcast. 122 * Can be used with {@link #getNetworkInfo(int)} to get {@link NetworkInfo} 123 * state based on the calling application. 124 * 125 * @see android.content.Intent#getIntExtra(String, int) 126 */ 127 public static final String EXTRA_NETWORK_TYPE = "networkType"; 128 129 /** 130 * The lookup key for a boolean that indicates whether a connect event 131 * is for a network to which the connectivity manager was failing over 132 * following a disconnect on another network. 133 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}. 134 */ 135 public static final String EXTRA_IS_FAILOVER = "isFailover"; 136 /** 137 * The lookup key for a {@link NetworkInfo} object. This is supplied when 138 * there is another network that it may be possible to connect to. Retrieve with 139 * {@link android.content.Intent#getParcelableExtra(String)}. 140 */ 141 public static final String EXTRA_OTHER_NETWORK_INFO = "otherNetwork"; 142 /** 143 * The lookup key for a boolean that indicates whether there is a 144 * complete lack of connectivity, i.e., no network is available. 145 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}. 146 */ 147 public static final String EXTRA_NO_CONNECTIVITY = "noConnectivity"; 148 /** 149 * The lookup key for a string that indicates why an attempt to connect 150 * to a network failed. The string has no particular structure. It is 151 * intended to be used in notifications presented to users. Retrieve 152 * it with {@link android.content.Intent#getStringExtra(String)}. 153 */ 154 public static final String EXTRA_REASON = "reason"; 155 /** 156 * The lookup key for a string that provides optionally supplied 157 * extra information about the network state. The information 158 * may be passed up from the lower networking layers, and its 159 * meaning may be specific to a particular network type. Retrieve 160 * it with {@link android.content.Intent#getStringExtra(String)}. 161 */ 162 public static final String EXTRA_EXTRA_INFO = "extraInfo"; 163 /** 164 * The lookup key for an int that provides information about 165 * our connection to the internet at large. 0 indicates no connection, 166 * 100 indicates a great connection. Retrieve it with 167 * {@link android.content.Intent#getIntExtra(String, int)}. 168 * {@hide} 169 */ 170 public static final String EXTRA_INET_CONDITION = "inetCondition"; 171 172 /** 173 * Broadcast action to indicate the change of data activity status 174 * (idle or active) on a network in a recent period. 175 * The network becomes active when data transmission is started, or 176 * idle if there is no data transmission for a period of time. 177 * {@hide} 178 */ 179 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) 180 public static final String ACTION_DATA_ACTIVITY_CHANGE = "android.net.conn.DATA_ACTIVITY_CHANGE"; 181 /** 182 * The lookup key for an enum that indicates the network device type on which this data activity 183 * change happens. 184 * {@hide} 185 */ 186 public static final String EXTRA_DEVICE_TYPE = "deviceType"; 187 /** 188 * The lookup key for a boolean that indicates the device is active or not. {@code true} means 189 * it is actively sending or receiving data and {@code false} means it is idle. 190 * {@hide} 191 */ 192 public static final String EXTRA_IS_ACTIVE = "isActive"; 193 /** 194 * The lookup key for a long that contains the timestamp (nanos) of the radio state change. 195 * {@hide} 196 */ 197 public static final String EXTRA_REALTIME_NS = "tsNanos"; 198 199 /** 200 * Broadcast Action: The setting for background data usage has changed 201 * values. Use {@link #getBackgroundDataSetting()} to get the current value. 202 * <p> 203 * If an application uses the network in the background, it should listen 204 * for this broadcast and stop using the background data if the value is 205 * {@code false}. 206 * <p> 207 * 208 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability 209 * of background data depends on several combined factors, and 210 * this broadcast is no longer sent. Instead, when background 211 * data is unavailable, {@link #getActiveNetworkInfo()} will now 212 * appear disconnected. During first boot after a platform 213 * upgrade, this broadcast will be sent once if 214 * {@link #getBackgroundDataSetting()} was {@code false} before 215 * the upgrade. 216 */ 217 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) 218 @Deprecated 219 public static final String ACTION_BACKGROUND_DATA_SETTING_CHANGED = 220 "android.net.conn.BACKGROUND_DATA_SETTING_CHANGED"; 221 222 /** 223 * Broadcast Action: The network connection may not be good 224 * uses {@code ConnectivityManager.EXTRA_INET_CONDITION} and 225 * {@code ConnectivityManager.EXTRA_NETWORK_INFO} to specify 226 * the network and it's condition. 227 * @hide 228 */ 229 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) 230 public static final String INET_CONDITION_ACTION = 231 "android.net.conn.INET_CONDITION_ACTION"; 232 233 /** 234 * Broadcast Action: A tetherable connection has come or gone. 235 * Uses {@code ConnectivityManager.EXTRA_AVAILABLE_TETHER}, 236 * {@code ConnectivityManager.EXTRA_ACTIVE_TETHER} and 237 * {@code ConnectivityManager.EXTRA_ERRORED_TETHER} to indicate 238 * the current state of tethering. Each include a list of 239 * interface names in that state (may be empty). 240 * @hide 241 */ 242 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) 243 public static final String ACTION_TETHER_STATE_CHANGED = 244 "android.net.conn.TETHER_STATE_CHANGED"; 245 246 /** 247 * @hide 248 * gives a String[] listing all the interfaces configured for 249 * tethering and currently available for tethering. 250 */ 251 public static final String EXTRA_AVAILABLE_TETHER = "availableArray"; 252 253 /** 254 * @hide 255 * gives a String[] listing all the interfaces currently tethered 256 * (ie, has dhcp support and packets potentially forwarded/NATed) 257 */ 258 public static final String EXTRA_ACTIVE_TETHER = "activeArray"; 259 260 /** 261 * @hide 262 * gives a String[] listing all the interfaces we tried to tether and 263 * failed. Use {@link #getLastTetherError} to find the error code 264 * for any interfaces listed here. 265 */ 266 public static final String EXTRA_ERRORED_TETHER = "erroredArray"; 267 268 /** 269 * Broadcast Action: The captive portal tracker has finished its test. 270 * Sent only while running Setup Wizard, in lieu of showing a user 271 * notification. 272 * @hide 273 */ 274 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) 275 public static final String ACTION_CAPTIVE_PORTAL_TEST_COMPLETED = 276 "android.net.conn.CAPTIVE_PORTAL_TEST_COMPLETED"; 277 /** 278 * The lookup key for a boolean that indicates whether a captive portal was detected. 279 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}. 280 * @hide 281 */ 282 public static final String EXTRA_IS_CAPTIVE_PORTAL = "captivePortal"; 283 284 /** 285 * The absence of a connection type. 286 * @hide 287 */ 288 public static final int TYPE_NONE = -1; 289 290 /** 291 * The Mobile data connection. When active, all data traffic 292 * will use this network type's interface by default 293 * (it has a default route) 294 */ 295 public static final int TYPE_MOBILE = 0; 296 /** 297 * The WIFI data connection. When active, all data traffic 298 * will use this network type's interface by default 299 * (it has a default route). 300 */ 301 public static final int TYPE_WIFI = 1; 302 /** 303 * An MMS-specific Mobile data connection. This network type may use the 304 * same network interface as {@link #TYPE_MOBILE} or it may use a different 305 * one. This is used by applications needing to talk to the carrier's 306 * Multimedia Messaging Service servers. 307 */ 308 public static final int TYPE_MOBILE_MMS = 2; 309 /** 310 * A SUPL-specific Mobile data connection. This network type may use the 311 * same network interface as {@link #TYPE_MOBILE} or it may use a different 312 * one. This is used by applications needing to talk to the carrier's 313 * Secure User Plane Location servers for help locating the device. 314 */ 315 public static final int TYPE_MOBILE_SUPL = 3; 316 /** 317 * A DUN-specific Mobile data connection. This network type may use the 318 * same network interface as {@link #TYPE_MOBILE} or it may use a different 319 * one. This is sometimes by the system when setting up an upstream connection 320 * for tethering so that the carrier is aware of DUN traffic. 321 */ 322 public static final int TYPE_MOBILE_DUN = 4; 323 /** 324 * A High Priority Mobile data connection. This network type uses the 325 * same network interface as {@link #TYPE_MOBILE} but the routing setup 326 * is different. Only requesting processes will have access to the 327 * Mobile DNS servers and only IP's explicitly requested via {@link #requestRouteToHost} 328 * will route over this interface if no default route exists. 329 */ 330 public static final int TYPE_MOBILE_HIPRI = 5; 331 /** 332 * The WiMAX data connection. When active, all data traffic 333 * will use this network type's interface by default 334 * (it has a default route). 335 */ 336 public static final int TYPE_WIMAX = 6; 337 338 /** 339 * The Bluetooth data connection. When active, all data traffic 340 * will use this network type's interface by default 341 * (it has a default route). 342 */ 343 public static final int TYPE_BLUETOOTH = 7; 344 345 /** 346 * Dummy data connection. This should not be used on shipping devices. 347 */ 348 public static final int TYPE_DUMMY = 8; 349 350 /** 351 * The Ethernet data connection. When active, all data traffic 352 * will use this network type's interface by default 353 * (it has a default route). 354 */ 355 public static final int TYPE_ETHERNET = 9; 356 357 /** 358 * Over the air Administration. 359 * {@hide} 360 */ 361 public static final int TYPE_MOBILE_FOTA = 10; 362 363 /** 364 * IP Multimedia Subsystem. 365 * {@hide} 366 */ 367 public static final int TYPE_MOBILE_IMS = 11; 368 369 /** 370 * Carrier Branded Services. 371 * {@hide} 372 */ 373 public static final int TYPE_MOBILE_CBS = 12; 374 375 /** 376 * A Wi-Fi p2p connection. Only requesting processes will have access to 377 * the peers connected. 378 * {@hide} 379 */ 380 public static final int TYPE_WIFI_P2P = 13; 381 382 /** 383 * The network to use for initially attaching to the network 384 * {@hide} 385 */ 386 public static final int TYPE_MOBILE_IA = 14; 387 388 /** 389 * The network that uses proxy to achieve connectivity. 390 * {@hide} 391 */ 392 public static final int TYPE_PROXY = 16; 393 394 /** {@hide} */ 395 public static final int MAX_RADIO_TYPE = TYPE_PROXY; 396 397 /** {@hide} */ 398 public static final int MAX_NETWORK_TYPE = TYPE_PROXY; 399 400 /** 401 * If you want to set the default network preference,you can directly 402 * change the networkAttributes array in framework's config.xml. 403 * 404 * @deprecated Since we support so many more networks now, the single 405 * network default network preference can't really express 406 * the hierarchy. Instead, the default is defined by the 407 * networkAttributes in config.xml. You can determine 408 * the current value by calling {@link #getNetworkPreference()} 409 * from an App. 410 */ 411 @Deprecated 412 public static final int DEFAULT_NETWORK_PREFERENCE = TYPE_WIFI; 413 414 /** 415 * Default value for {@link Settings.Global#CONNECTIVITY_CHANGE_DELAY} in 416 * milliseconds. This was introduced because IPv6 routes seem to take a 417 * moment to settle - trying network activity before the routes are adjusted 418 * can lead to packets using the wrong interface or having the wrong IP address. 419 * This delay is a bit crude, but in the future hopefully we will have kernel 420 * notifications letting us know when it's safe to use the new network. 421 * 422 * @hide 423 */ 424 public static final int CONNECTIVITY_CHANGE_DELAY_DEFAULT = 3000; 425 426 /** 427 * @hide 428 */ 429 public final static int INVALID_NET_ID = 0; 430 431 private final IConnectivityManager mService; 432 433 private final String mPackageName; 434 435 private INetworkManagementService mNMService; 436 437 /** 438 * Tests if a given integer represents a valid network type. 439 * @param networkType the type to be tested 440 * @return a boolean. {@code true} if the type is valid, else {@code false} 441 */ 442 public static boolean isNetworkTypeValid(int networkType) { 443 return networkType >= 0 && networkType <= MAX_NETWORK_TYPE; 444 } 445 446 /** 447 * Returns a non-localized string representing a given network type. 448 * ONLY used for debugging output. 449 * @param type the type needing naming 450 * @return a String for the given type, or a string version of the type ("87") 451 * if no name is known. 452 * {@hide} 453 */ 454 public static String getNetworkTypeName(int type) { 455 switch (type) { 456 case TYPE_MOBILE: 457 return "MOBILE"; 458 case TYPE_WIFI: 459 return "WIFI"; 460 case TYPE_MOBILE_MMS: 461 return "MOBILE_MMS"; 462 case TYPE_MOBILE_SUPL: 463 return "MOBILE_SUPL"; 464 case TYPE_MOBILE_DUN: 465 return "MOBILE_DUN"; 466 case TYPE_MOBILE_HIPRI: 467 return "MOBILE_HIPRI"; 468 case TYPE_WIMAX: 469 return "WIMAX"; 470 case TYPE_BLUETOOTH: 471 return "BLUETOOTH"; 472 case TYPE_DUMMY: 473 return "DUMMY"; 474 case TYPE_ETHERNET: 475 return "ETHERNET"; 476 case TYPE_MOBILE_FOTA: 477 return "MOBILE_FOTA"; 478 case TYPE_MOBILE_IMS: 479 return "MOBILE_IMS"; 480 case TYPE_MOBILE_CBS: 481 return "MOBILE_CBS"; 482 case TYPE_WIFI_P2P: 483 return "WIFI_P2P"; 484 case TYPE_MOBILE_IA: 485 return "MOBILE_IA"; 486 case TYPE_PROXY: 487 return "PROXY"; 488 default: 489 return Integer.toString(type); 490 } 491 } 492 493 /** 494 * Checks if a given type uses the cellular data connection. 495 * This should be replaced in the future by a network property. 496 * @param networkType the type to check 497 * @return a boolean - {@code true} if uses cellular network, else {@code false} 498 * {@hide} 499 */ 500 public static boolean isNetworkTypeMobile(int networkType) { 501 switch (networkType) { 502 case TYPE_MOBILE: 503 case TYPE_MOBILE_MMS: 504 case TYPE_MOBILE_SUPL: 505 case TYPE_MOBILE_DUN: 506 case TYPE_MOBILE_HIPRI: 507 case TYPE_MOBILE_FOTA: 508 case TYPE_MOBILE_IMS: 509 case TYPE_MOBILE_CBS: 510 case TYPE_MOBILE_IA: 511 return true; 512 default: 513 return false; 514 } 515 } 516 517 /** 518 * Checks if the given network type is backed by a Wi-Fi radio. 519 * 520 * @hide 521 */ 522 public static boolean isNetworkTypeWifi(int networkType) { 523 switch (networkType) { 524 case TYPE_WIFI: 525 case TYPE_WIFI_P2P: 526 return true; 527 default: 528 return false; 529 } 530 } 531 532 /** 533 * Checks if the given network type should be exempt from VPN routing rules 534 * 535 * @hide 536 */ 537 public static boolean isNetworkTypeExempt(int networkType) { 538 switch (networkType) { 539 case TYPE_MOBILE_MMS: 540 case TYPE_MOBILE_SUPL: 541 case TYPE_MOBILE_HIPRI: 542 case TYPE_MOBILE_IA: 543 return true; 544 default: 545 return false; 546 } 547 } 548 549 /** 550 * Specifies the preferred network type. When the device has more 551 * than one type available the preferred network type will be used. 552 * 553 * @param preference the network type to prefer over all others. It is 554 * unspecified what happens to the old preferred network in the 555 * overall ordering. 556 * @deprecated Functionality has been removed as it no longer makes sense, 557 * with many more than two networks - we'd need an array to express 558 * preference. Instead we use dynamic network properties of 559 * the networks to describe their precedence. 560 */ 561 public void setNetworkPreference(int preference) { 562 } 563 564 /** 565 * Retrieves the current preferred network type. 566 * 567 * @return an integer representing the preferred network type 568 * 569 * <p>This method requires the caller to hold the permission 570 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}. 571 * @deprecated Functionality has been removed as it no longer makes sense, 572 * with many more than two networks - we'd need an array to express 573 * preference. Instead we use dynamic network properties of 574 * the networks to describe their precedence. 575 */ 576 public int getNetworkPreference() { 577 return TYPE_NONE; 578 } 579 580 /** 581 * Returns details about the currently active default data network. When 582 * connected, this network is the default route for outgoing connections. 583 * You should always check {@link NetworkInfo#isConnected()} before initiating 584 * network traffic. This may return {@code null} when there is no default 585 * network. 586 * 587 * @return a {@link NetworkInfo} object for the current default network 588 * or {@code null} if no network default network is currently active 589 * 590 * <p>This method requires the call to hold the permission 591 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}. 592 */ 593 public NetworkInfo getActiveNetworkInfo() { 594 try { 595 return mService.getActiveNetworkInfo(); 596 } catch (RemoteException e) { 597 return null; 598 } 599 } 600 601 /** 602 * Returns details about the currently active default data network 603 * for a given uid. This is for internal use only to avoid spying 604 * other apps. 605 * 606 * @return a {@link NetworkInfo} object for the current default network 607 * for the given uid or {@code null} if no default network is 608 * available for the specified uid. 609 * 610 * <p>This method requires the caller to hold the permission 611 * {@link android.Manifest.permission#CONNECTIVITY_INTERNAL} 612 * {@hide} 613 */ 614 public NetworkInfo getActiveNetworkInfoForUid(int uid) { 615 try { 616 return mService.getActiveNetworkInfoForUid(uid); 617 } catch (RemoteException e) { 618 return null; 619 } 620 } 621 622 /** 623 * Returns connection status information about a particular 624 * network type. 625 * 626 * @param networkType integer specifying which networkType in 627 * which you're interested. 628 * @return a {@link NetworkInfo} object for the requested 629 * network type or {@code null} if the type is not 630 * supported by the device. 631 * 632 * <p>This method requires the call to hold the permission 633 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}. 634 */ 635 public NetworkInfo getNetworkInfo(int networkType) { 636 try { 637 return mService.getNetworkInfo(networkType); 638 } catch (RemoteException e) { 639 return null; 640 } 641 } 642 643 /** 644 * Returns connection status information about all network 645 * types supported by the device. 646 * 647 * @return an array of {@link NetworkInfo} objects. Check each 648 * {@link NetworkInfo#getType} for which type each applies. 649 * 650 * <p>This method requires the call to hold the permission 651 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}. 652 */ 653 public NetworkInfo[] getAllNetworkInfo() { 654 try { 655 return mService.getAllNetworkInfo(); 656 } catch (RemoteException e) { 657 return null; 658 } 659 } 660 661 /** 662 * Returns details about the Provisioning or currently active default data network. When 663 * connected, this network is the default route for outgoing connections. 664 * You should always check {@link NetworkInfo#isConnected()} before initiating 665 * network traffic. This may return {@code null} when there is no default 666 * network. 667 * 668 * @return a {@link NetworkInfo} object for the current default network 669 * or {@code null} if no network default network is currently active 670 * 671 * <p>This method requires the call to hold the permission 672 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}. 673 * 674 * {@hide} 675 */ 676 public NetworkInfo getProvisioningOrActiveNetworkInfo() { 677 try { 678 return mService.getProvisioningOrActiveNetworkInfo(); 679 } catch (RemoteException e) { 680 return null; 681 } 682 } 683 684 /** 685 * Returns the IP information for the current default network. 686 * 687 * @return a {@link LinkProperties} object describing the IP info 688 * for the current default network, or {@code null} if there 689 * is no current default network. 690 * 691 * <p>This method requires the call to hold the permission 692 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}. 693 * {@hide} 694 */ 695 public LinkProperties getActiveLinkProperties() { 696 try { 697 return mService.getActiveLinkProperties(); 698 } catch (RemoteException e) { 699 return null; 700 } 701 } 702 703 /** 704 * Returns the IP information for a given network type. 705 * 706 * @param networkType the network type of interest. 707 * @return a {@link LinkProperties} object describing the IP info 708 * for the given networkType, or {@code null} if there is 709 * no current default network. 710 * 711 * <p>This method requires the call to hold the permission 712 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}. 713 * {@hide} 714 */ 715 public LinkProperties getLinkProperties(int networkType) { 716 try { 717 return mService.getLinkPropertiesForType(networkType); 718 } catch (RemoteException e) { 719 return null; 720 } 721 } 722 723 /** 724 * Get the {@link LinkProperties} for the given {@link Network}. This 725 * will return {@code null} if the network is unknown. 726 * 727 * @param network The {@link Network} object identifying the network in question. 728 * @return The {@link LinkProperties} for the network, or {@code null}. 729 **/ 730 public LinkProperties getLinkProperties(Network network) { 731 try { 732 return mService.getLinkProperties(network); 733 } catch (RemoteException e) { 734 return null; 735 } 736 } 737 738 /** 739 * Get the {@link NetworkCapabilities} for the given {@link Network}. This 740 * will return {@code null} if the network is unknown. 741 * 742 * @param network The {@link Network} object identifying the network in question. 743 * @return The {@link NetworkCapabilities} for the network, or {@code null}. 744 */ 745 public NetworkCapabilities getNetworkCapabilities(Network network) { 746 try { 747 return mService.getNetworkCapabilities(network); 748 } catch (RemoteException e) { 749 return null; 750 } 751 } 752 753 /** 754 * Tells each network type to set its radio power state as directed. 755 * 756 * @param turnOn a boolean, {@code true} to turn the radios on, 757 * {@code false} to turn them off. 758 * @return a boolean, {@code true} indicating success. All network types 759 * will be tried, even if some fail. 760 * 761 * <p>This method requires the call to hold the permission 762 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE}. 763 * {@hide} 764 */ 765// TODO - check for any callers and remove 766// public boolean setRadios(boolean turnOn) { 767// try { 768// return mService.setRadios(turnOn); 769// } catch (RemoteException e) { 770// return false; 771// } 772// } 773 774 /** 775 * Tells a given networkType to set its radio power state as directed. 776 * 777 * @param networkType the int networkType of interest. 778 * @param turnOn a boolean, {@code true} to turn the radio on, 779 * {@code} false to turn it off. 780 * @return a boolean, {@code true} indicating success. 781 * 782 * <p>This method requires the call to hold the permission 783 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE}. 784 * {@hide} 785 */ 786// TODO - check for any callers and remove 787// public boolean setRadio(int networkType, boolean turnOn) { 788// try { 789// return mService.setRadio(networkType, turnOn); 790// } catch (RemoteException e) { 791// return false; 792// } 793// } 794 795 /** 796 * Tells the underlying networking system that the caller wants to 797 * begin using the named feature. The interpretation of {@code feature} 798 * is completely up to each networking implementation. 799 * <p>This method requires the caller to hold the permission 800 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE}. 801 * @param networkType specifies which network the request pertains to 802 * @param feature the name of the feature to be used 803 * @return an integer value representing the outcome of the request. 804 * The interpretation of this value is specific to each networking 805 * implementation+feature combination, except that the value {@code -1} 806 * always indicates failure. 807 * 808 * @deprecated Deprecated in favor of the cleaner {@link #requestNetwork} api. 809 */ 810 public int startUsingNetworkFeature(int networkType, String feature) { 811 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature); 812 if (netCap == null) { 813 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " + 814 feature); 815 return PhoneConstants.APN_REQUEST_FAILED; 816 } 817 818 NetworkRequest request = null; 819 synchronized (sLegacyRequests) { 820 LegacyRequest l = sLegacyRequests.get(netCap); 821 if (l != null) { 822 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest); 823 renewRequestLocked(l); 824 if (l.currentNetwork != null) { 825 return PhoneConstants.APN_ALREADY_ACTIVE; 826 } else { 827 return PhoneConstants.APN_REQUEST_STARTED; 828 } 829 } 830 831 request = requestNetworkForFeatureLocked(netCap); 832 } 833 if (request != null) { 834 Log.d(TAG, "starting startUsingNeworkFeature for request " + request); 835 return PhoneConstants.APN_REQUEST_STARTED; 836 } else { 837 Log.d(TAG, " request Failed"); 838 return PhoneConstants.APN_REQUEST_FAILED; 839 } 840 } 841 842 /** 843 * Tells the underlying networking system that the caller is finished 844 * using the named feature. The interpretation of {@code feature} 845 * is completely up to each networking implementation. 846 * <p>This method requires the caller to hold the permission 847 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE}. 848 * @param networkType specifies which network the request pertains to 849 * @param feature the name of the feature that is no longer needed 850 * @return an integer value representing the outcome of the request. 851 * The interpretation of this value is specific to each networking 852 * implementation+feature combination, except that the value {@code -1} 853 * always indicates failure. 854 * 855 * @deprecated Deprecated in favor of the cleaner {@link #requestNetwork} api. 856 */ 857 public int stopUsingNetworkFeature(int networkType, String feature) { 858 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature); 859 if (netCap == null) { 860 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " + 861 feature); 862 return -1; 863 } 864 865 NetworkRequest request = removeRequestForFeature(netCap); 866 if (request != null) { 867 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature); 868 releaseNetworkRequest(request); 869 } 870 return 1; 871 } 872 873 /** 874 * Removes the NET_CAPABILITY_NOT_RESTRICTED capability from the given 875 * NetworkCapabilities object if all the capabilities it provides are 876 * typically provided by restricted networks. 877 * 878 * TODO: consider: 879 * - Moving to NetworkCapabilities 880 * - Renaming it to guessRestrictedCapability and make it set the 881 * restricted capability bit in addition to clearing it. 882 * @hide 883 */ 884 public static void maybeMarkCapabilitiesRestricted(NetworkCapabilities nc) { 885 for (Integer capability : nc.getNetworkCapabilities()) { 886 switch (capability.intValue()) { 887 case NetworkCapabilities.NET_CAPABILITY_CBS: 888 case NetworkCapabilities.NET_CAPABILITY_DUN: 889 case NetworkCapabilities.NET_CAPABILITY_EIMS: 890 case NetworkCapabilities.NET_CAPABILITY_FOTA: 891 case NetworkCapabilities.NET_CAPABILITY_IA: 892 case NetworkCapabilities.NET_CAPABILITY_IMS: 893 case NetworkCapabilities.NET_CAPABILITY_RCS: 894 case NetworkCapabilities.NET_CAPABILITY_XCAP: 895 case NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED: //there by default 896 continue; 897 default: 898 // At least one capability usually provided by unrestricted 899 // networks. Conclude that this network is unrestricted. 900 return; 901 } 902 } 903 // All the capabilities are typically provided by restricted networks. 904 // Conclude that this network is restricted. 905 nc.removeNetworkCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED); 906 } 907 908 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) { 909 if (networkType == TYPE_MOBILE) { 910 int cap = -1; 911 if ("enableMMS".equals(feature)) { 912 cap = NetworkCapabilities.NET_CAPABILITY_MMS; 913 } else if ("enableSUPL".equals(feature)) { 914 cap = NetworkCapabilities.NET_CAPABILITY_SUPL; 915 } else if ("enableDUN".equals(feature) || "enableDUNAlways".equals(feature)) { 916 cap = NetworkCapabilities.NET_CAPABILITY_DUN; 917 } else if ("enableHIPRI".equals(feature)) { 918 cap = NetworkCapabilities.NET_CAPABILITY_INTERNET; 919 } else if ("enableFOTA".equals(feature)) { 920 cap = NetworkCapabilities.NET_CAPABILITY_FOTA; 921 } else if ("enableIMS".equals(feature)) { 922 cap = NetworkCapabilities.NET_CAPABILITY_IMS; 923 } else if ("enableCBS".equals(feature)) { 924 cap = NetworkCapabilities.NET_CAPABILITY_CBS; 925 } else { 926 return null; 927 } 928 NetworkCapabilities netCap = new NetworkCapabilities(); 929 netCap.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR); 930 netCap.addNetworkCapability(cap); 931 maybeMarkCapabilitiesRestricted(netCap); 932 return netCap; 933 } else if (networkType == TYPE_WIFI) { 934 if ("p2p".equals(feature)) { 935 NetworkCapabilities netCap = new NetworkCapabilities(); 936 netCap.addTransportType(NetworkCapabilities.TRANSPORT_WIFI); 937 netCap.addNetworkCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P); 938 maybeMarkCapabilitiesRestricted(netCap); 939 return netCap; 940 } 941 } 942 return null; 943 } 944 945 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) { 946 if (netCap == null) return TYPE_NONE; 947 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) { 948 return TYPE_MOBILE_CBS; 949 } 950 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) { 951 return TYPE_MOBILE_IMS; 952 } 953 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) { 954 return TYPE_MOBILE_FOTA; 955 } 956 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) { 957 return TYPE_MOBILE_DUN; 958 } 959 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) { 960 return TYPE_MOBILE_SUPL; 961 } 962 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) { 963 return TYPE_MOBILE_MMS; 964 } 965 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) { 966 return TYPE_MOBILE_HIPRI; 967 } 968 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) { 969 return TYPE_WIFI_P2P; 970 } 971 return TYPE_NONE; 972 } 973 974 private static class LegacyRequest { 975 NetworkCapabilities networkCapabilities; 976 NetworkRequest networkRequest; 977 int expireSequenceNumber; 978 Network currentNetwork; 979 int delay = -1; 980 NetworkCallbackListener networkCallbackListener = new NetworkCallbackListener() { 981 @Override 982 public void onAvailable(NetworkRequest request, Network network) { 983 currentNetwork = network; 984 Log.d(TAG, "startUsingNetworkFeature got Network:" + network); 985 network.bindProcessForHostResolution(); 986 } 987 @Override 988 public void onLost(NetworkRequest request, Network network) { 989 if (network.equals(currentNetwork)) { 990 currentNetwork = null; 991 network.unbindProcessForHostResolution(); 992 } 993 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network); 994 } 995 }; 996 } 997 998 private HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests = 999 new HashMap<NetworkCapabilities, LegacyRequest>(); 1000 1001 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) { 1002 synchronized (sLegacyRequests) { 1003 LegacyRequest l = sLegacyRequests.get(netCap); 1004 if (l != null) return l.networkRequest; 1005 } 1006 return null; 1007 } 1008 1009 private void renewRequestLocked(LegacyRequest l) { 1010 l.expireSequenceNumber++; 1011 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber); 1012 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay); 1013 } 1014 1015 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) { 1016 int ourSeqNum = -1; 1017 synchronized (sLegacyRequests) { 1018 LegacyRequest l = sLegacyRequests.get(netCap); 1019 if (l == null) return; 1020 ourSeqNum = l.expireSequenceNumber; 1021 if (l.expireSequenceNumber == sequenceNum) { 1022 releaseNetworkRequest(l.networkRequest); 1023 sLegacyRequests.remove(netCap); 1024 } 1025 } 1026 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum); 1027 } 1028 1029 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) { 1030 int delay = -1; 1031 int type = legacyTypeForNetworkCapabilities(netCap); 1032 try { 1033 delay = mService.getRestoreDefaultNetworkDelay(type); 1034 } catch (RemoteException e) {} 1035 LegacyRequest l = new LegacyRequest(); 1036 l.networkCapabilities = netCap; 1037 l.delay = delay; 1038 l.expireSequenceNumber = 0; 1039 l.networkRequest = sendRequestForNetwork(netCap, l.networkCallbackListener, 0, 1040 REQUEST, type); 1041 if (l.networkRequest == null) return null; 1042 sLegacyRequests.put(netCap, l); 1043 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay); 1044 return l.networkRequest; 1045 } 1046 1047 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) { 1048 if (delay >= 0) { 1049 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay); 1050 Message msg = sCallbackHandler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap); 1051 sCallbackHandler.sendMessageDelayed(msg, delay); 1052 } 1053 } 1054 1055 private NetworkRequest removeRequestForFeature(NetworkCapabilities netCap) { 1056 synchronized (sLegacyRequests) { 1057 LegacyRequest l = sLegacyRequests.remove(netCap); 1058 if (l == null) return null; 1059 return l.networkRequest; 1060 } 1061 } 1062 1063 /** 1064 * Ensure that a network route exists to deliver traffic to the specified 1065 * host via the specified network interface. An attempt to add a route that 1066 * already exists is ignored, but treated as successful. 1067 * <p>This method requires the caller to hold the permission 1068 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE}. 1069 * @param networkType the type of the network over which traffic to the specified 1070 * host is to be routed 1071 * @param hostAddress the IP address of the host to which the route is desired 1072 * @return {@code true} on success, {@code false} on failure 1073 * 1074 * @deprecated Deprecated in favor of the {@link #requestNetwork}, 1075 * {@link Network#bindProcess} and {@link Network#socketFactory} api. 1076 */ 1077 public boolean requestRouteToHost(int networkType, int hostAddress) { 1078 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress); 1079 1080 if (inetAddress == null) { 1081 return false; 1082 } 1083 1084 return requestRouteToHostAddress(networkType, inetAddress); 1085 } 1086 1087 /** 1088 * Ensure that a network route exists to deliver traffic to the specified 1089 * host via the specified network interface. An attempt to add a route that 1090 * already exists is ignored, but treated as successful. 1091 * <p>This method requires the caller to hold the permission 1092 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE}. 1093 * @param networkType the type of the network over which traffic to the specified 1094 * host is to be routed 1095 * @param hostAddress the IP address of the host to which the route is desired 1096 * @return {@code true} on success, {@code false} on failure 1097 * @hide 1098 * @deprecated Deprecated in favor of the {@link #requestNetwork} and 1099 * {@link Network#bindProcess} api. 1100 */ 1101 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) { 1102 byte[] address = hostAddress.getAddress(); 1103 try { 1104 return mService.requestRouteToHostAddress(networkType, address, mPackageName); 1105 } catch (RemoteException e) { 1106 return false; 1107 } 1108 } 1109 1110 /** 1111 * Returns the value of the setting for background data usage. If false, 1112 * applications should not use the network if the application is not in the 1113 * foreground. Developers should respect this setting, and check the value 1114 * of this before performing any background data operations. 1115 * <p> 1116 * All applications that have background services that use the network 1117 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}. 1118 * <p> 1119 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of 1120 * background data depends on several combined factors, and this method will 1121 * always return {@code true}. Instead, when background data is unavailable, 1122 * {@link #getActiveNetworkInfo()} will now appear disconnected. 1123 * 1124 * @return Whether background data usage is allowed. 1125 */ 1126 @Deprecated 1127 public boolean getBackgroundDataSetting() { 1128 // assume that background data is allowed; final authority is 1129 // NetworkInfo which may be blocked. 1130 return true; 1131 } 1132 1133 /** 1134 * Sets the value of the setting for background data usage. 1135 * 1136 * @param allowBackgroundData Whether an application should use data while 1137 * it is in the background. 1138 * 1139 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING 1140 * @see #getBackgroundDataSetting() 1141 * @hide 1142 */ 1143 @Deprecated 1144 public void setBackgroundDataSetting(boolean allowBackgroundData) { 1145 // ignored 1146 } 1147 1148 /** 1149 * Return quota status for the current active network, or {@code null} if no 1150 * network is active. Quota status can change rapidly, so these values 1151 * shouldn't be cached. 1152 * 1153 * <p>This method requires the call to hold the permission 1154 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}. 1155 * 1156 * @hide 1157 */ 1158 public NetworkQuotaInfo getActiveNetworkQuotaInfo() { 1159 try { 1160 return mService.getActiveNetworkQuotaInfo(); 1161 } catch (RemoteException e) { 1162 return null; 1163 } 1164 } 1165 1166 /** 1167 * @hide 1168 * @deprecated Talk to TelephonyManager directly 1169 */ 1170 public boolean getMobileDataEnabled() { 1171 IBinder b = ServiceManager.getService(Context.TELEPHONY_SERVICE); 1172 if (b != null) { 1173 try { 1174 ITelephony it = ITelephony.Stub.asInterface(b); 1175 return it.getDataEnabled(); 1176 } catch (RemoteException e) { } 1177 } 1178 return false; 1179 } 1180 1181 /** 1182 * Callback for use with {@link ConnectivityManager#registerNetworkActiveListener} to 1183 * find out when the current network has gone in to a high power state. 1184 */ 1185 public interface OnNetworkActiveListener { 1186 /** 1187 * Called on the main thread of the process to report that the current data network 1188 * has become active, and it is now a good time to perform any pending network 1189 * operations. Note that this listener only tells you when the network becomes 1190 * active; if at any other time you want to know whether it is active (and thus okay 1191 * to initiate network traffic), you can retrieve its instantaneous state with 1192 * {@link ConnectivityManager#isNetworkActive}. 1193 */ 1194 public void onNetworkActive(); 1195 } 1196 1197 private INetworkManagementService getNetworkManagementService() { 1198 synchronized (this) { 1199 if (mNMService != null) { 1200 return mNMService; 1201 } 1202 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE); 1203 mNMService = INetworkManagementService.Stub.asInterface(b); 1204 return mNMService; 1205 } 1206 } 1207 1208 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener> 1209 mNetworkActivityListeners 1210 = new ArrayMap<OnNetworkActiveListener, INetworkActivityListener>(); 1211 1212 /** 1213 * Start listening to reports when the data network is active, meaning it is 1214 * a good time to perform network traffic. Use {@link #isNetworkActive()} 1215 * to determine the current state of the network after registering the listener. 1216 * 1217 * @param l The listener to be told when the network is active. 1218 */ 1219 public void registerNetworkActiveListener(final OnNetworkActiveListener l) { 1220 INetworkActivityListener rl = new INetworkActivityListener.Stub() { 1221 @Override 1222 public void onNetworkActive() throws RemoteException { 1223 l.onNetworkActive(); 1224 } 1225 }; 1226 1227 try { 1228 getNetworkManagementService().registerNetworkActivityListener(rl); 1229 mNetworkActivityListeners.put(l, rl); 1230 } catch (RemoteException e) { 1231 } 1232 } 1233 1234 /** 1235 * Remove network active listener previously registered with 1236 * {@link #registerNetworkActiveListener}. 1237 * 1238 * @param l Previously registered listener. 1239 */ 1240 public void unregisterNetworkActiveListener(OnNetworkActiveListener l) { 1241 INetworkActivityListener rl = mNetworkActivityListeners.get(l); 1242 if (rl == null) { 1243 throw new IllegalArgumentException("Listener not registered: " + l); 1244 } 1245 try { 1246 getNetworkManagementService().unregisterNetworkActivityListener(rl); 1247 } catch (RemoteException e) { 1248 } 1249 } 1250 1251 /** 1252 * Return whether the data network is currently active. An active network means that 1253 * it is currently in a high power state for performing data transmission. On some 1254 * types of networks, it may be expensive to move and stay in such a state, so it is 1255 * more power efficient to batch network traffic together when the radio is already in 1256 * this state. This method tells you whether right now is currently a good time to 1257 * initiate network traffic, as the network is already active. 1258 */ 1259 public boolean isNetworkActive() { 1260 try { 1261 return getNetworkManagementService().isNetworkActive(); 1262 } catch (RemoteException e) { 1263 } 1264 return false; 1265 } 1266 1267 /** 1268 * {@hide} 1269 */ 1270 public ConnectivityManager(IConnectivityManager service, String packageName) { 1271 mService = checkNotNull(service, "missing IConnectivityManager"); 1272 mPackageName = checkNotNull(packageName, "missing package name"); 1273 } 1274 1275 /** {@hide} */ 1276 public static ConnectivityManager from(Context context) { 1277 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 1278 } 1279 1280 /** 1281 * Get the set of tetherable, available interfaces. This list is limited by 1282 * device configuration and current interface existence. 1283 * 1284 * @return an array of 0 or more Strings of tetherable interface names. 1285 * 1286 * <p>This method requires the call to hold the permission 1287 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}. 1288 * {@hide} 1289 */ 1290 public String[] getTetherableIfaces() { 1291 try { 1292 return mService.getTetherableIfaces(); 1293 } catch (RemoteException e) { 1294 return new String[0]; 1295 } 1296 } 1297 1298 /** 1299 * Get the set of tethered interfaces. 1300 * 1301 * @return an array of 0 or more String of currently tethered interface names. 1302 * 1303 * <p>This method requires the call to hold the permission 1304 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}. 1305 * {@hide} 1306 */ 1307 public String[] getTetheredIfaces() { 1308 try { 1309 return mService.getTetheredIfaces(); 1310 } catch (RemoteException e) { 1311 return new String[0]; 1312 } 1313 } 1314 1315 /** 1316 * Get the set of interface names which attempted to tether but 1317 * failed. Re-attempting to tether may cause them to reset to the Tethered 1318 * state. Alternatively, causing the interface to be destroyed and recreated 1319 * may cause them to reset to the available state. 1320 * {@link ConnectivityManager#getLastTetherError} can be used to get more 1321 * information on the cause of the errors. 1322 * 1323 * @return an array of 0 or more String indicating the interface names 1324 * which failed to tether. 1325 * 1326 * <p>This method requires the call to hold the permission 1327 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}. 1328 * {@hide} 1329 */ 1330 public String[] getTetheringErroredIfaces() { 1331 try { 1332 return mService.getTetheringErroredIfaces(); 1333 } catch (RemoteException e) { 1334 return new String[0]; 1335 } 1336 } 1337 1338 /** 1339 * Attempt to tether the named interface. This will setup a dhcp server 1340 * on the interface, forward and NAT IP packets and forward DNS requests 1341 * to the best active upstream network interface. Note that if no upstream 1342 * IP network interface is available, dhcp will still run and traffic will be 1343 * allowed between the tethered devices and this device, though upstream net 1344 * access will of course fail until an upstream network interface becomes 1345 * active. 1346 * 1347 * @param iface the interface name to tether. 1348 * @return error a {@code TETHER_ERROR} value indicating success or failure type 1349 * 1350 * <p>This method requires the call to hold the permission 1351 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE}. 1352 * {@hide} 1353 */ 1354 public int tether(String iface) { 1355 try { 1356 return mService.tether(iface); 1357 } catch (RemoteException e) { 1358 return TETHER_ERROR_SERVICE_UNAVAIL; 1359 } 1360 } 1361 1362 /** 1363 * Stop tethering the named interface. 1364 * 1365 * @param iface the interface name to untether. 1366 * @return error a {@code TETHER_ERROR} value indicating success or failure type 1367 * 1368 * <p>This method requires the call to hold the permission 1369 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE}. 1370 * {@hide} 1371 */ 1372 public int untether(String iface) { 1373 try { 1374 return mService.untether(iface); 1375 } catch (RemoteException e) { 1376 return TETHER_ERROR_SERVICE_UNAVAIL; 1377 } 1378 } 1379 1380 /** 1381 * Check if the device allows for tethering. It may be disabled via 1382 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or 1383 * due to device configuration. 1384 * 1385 * @return a boolean - {@code true} indicating Tethering is supported. 1386 * 1387 * <p>This method requires the call to hold the permission 1388 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}. 1389 * {@hide} 1390 */ 1391 public boolean isTetheringSupported() { 1392 try { 1393 return mService.isTetheringSupported(); 1394 } catch (RemoteException e) { 1395 return false; 1396 } 1397 } 1398 1399 /** 1400 * Get the list of regular expressions that define any tetherable 1401 * USB network interfaces. If USB tethering is not supported by the 1402 * device, this list should be empty. 1403 * 1404 * @return an array of 0 or more regular expression Strings defining 1405 * what interfaces are considered tetherable usb interfaces. 1406 * 1407 * <p>This method requires the call to hold the permission 1408 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}. 1409 * {@hide} 1410 */ 1411 public String[] getTetherableUsbRegexs() { 1412 try { 1413 return mService.getTetherableUsbRegexs(); 1414 } catch (RemoteException e) { 1415 return new String[0]; 1416 } 1417 } 1418 1419 /** 1420 * Get the list of regular expressions that define any tetherable 1421 * Wifi network interfaces. If Wifi tethering is not supported by the 1422 * device, this list should be empty. 1423 * 1424 * @return an array of 0 or more regular expression Strings defining 1425 * what interfaces are considered tetherable wifi interfaces. 1426 * 1427 * <p>This method requires the call to hold the permission 1428 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}. 1429 * {@hide} 1430 */ 1431 public String[] getTetherableWifiRegexs() { 1432 try { 1433 return mService.getTetherableWifiRegexs(); 1434 } catch (RemoteException e) { 1435 return new String[0]; 1436 } 1437 } 1438 1439 /** 1440 * Get the list of regular expressions that define any tetherable 1441 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the 1442 * device, this list should be empty. 1443 * 1444 * @return an array of 0 or more regular expression Strings defining 1445 * what interfaces are considered tetherable bluetooth interfaces. 1446 * 1447 * <p>This method requires the call to hold the permission 1448 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}. 1449 * {@hide} 1450 */ 1451 public String[] getTetherableBluetoothRegexs() { 1452 try { 1453 return mService.getTetherableBluetoothRegexs(); 1454 } catch (RemoteException e) { 1455 return new String[0]; 1456 } 1457 } 1458 1459 /** 1460 * Attempt to both alter the mode of USB and Tethering of USB. A 1461 * utility method to deal with some of the complexity of USB - will 1462 * attempt to switch to Rndis and subsequently tether the resulting 1463 * interface on {@code true} or turn off tethering and switch off 1464 * Rndis on {@code false}. 1465 * 1466 * @param enable a boolean - {@code true} to enable tethering 1467 * @return error a {@code TETHER_ERROR} value indicating success or failure type 1468 * 1469 * <p>This method requires the call to hold the permission 1470 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE}. 1471 * {@hide} 1472 */ 1473 public int setUsbTethering(boolean enable) { 1474 try { 1475 return mService.setUsbTethering(enable); 1476 } catch (RemoteException e) { 1477 return TETHER_ERROR_SERVICE_UNAVAIL; 1478 } 1479 } 1480 1481 /** {@hide} */ 1482 public static final int TETHER_ERROR_NO_ERROR = 0; 1483 /** {@hide} */ 1484 public static final int TETHER_ERROR_UNKNOWN_IFACE = 1; 1485 /** {@hide} */ 1486 public static final int TETHER_ERROR_SERVICE_UNAVAIL = 2; 1487 /** {@hide} */ 1488 public static final int TETHER_ERROR_UNSUPPORTED = 3; 1489 /** {@hide} */ 1490 public static final int TETHER_ERROR_UNAVAIL_IFACE = 4; 1491 /** {@hide} */ 1492 public static final int TETHER_ERROR_MASTER_ERROR = 5; 1493 /** {@hide} */ 1494 public static final int TETHER_ERROR_TETHER_IFACE_ERROR = 6; 1495 /** {@hide} */ 1496 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR = 7; 1497 /** {@hide} */ 1498 public static final int TETHER_ERROR_ENABLE_NAT_ERROR = 8; 1499 /** {@hide} */ 1500 public static final int TETHER_ERROR_DISABLE_NAT_ERROR = 9; 1501 /** {@hide} */ 1502 public static final int TETHER_ERROR_IFACE_CFG_ERROR = 10; 1503 1504 /** 1505 * Get a more detailed error code after a Tethering or Untethering 1506 * request asynchronously failed. 1507 * 1508 * @param iface The name of the interface of interest 1509 * @return error The error code of the last error tethering or untethering the named 1510 * interface 1511 * 1512 * <p>This method requires the call to hold the permission 1513 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}. 1514 * {@hide} 1515 */ 1516 public int getLastTetherError(String iface) { 1517 try { 1518 return mService.getLastTetherError(iface); 1519 } catch (RemoteException e) { 1520 return TETHER_ERROR_SERVICE_UNAVAIL; 1521 } 1522 } 1523 1524 /** 1525 * Try to ensure the device stays awake until we connect with the next network. 1526 * Actually just holds a wakelock for a number of seconds while we try to connect 1527 * to any default networks. This will expire if the timeout passes or if we connect 1528 * to a default after this is called. For internal use only. 1529 * 1530 * @param forWhom the name of the network going down for logging purposes 1531 * @return {@code true} on success, {@code false} on failure 1532 * 1533 * <p>This method requires the call to hold the permission 1534 * {@link android.Manifest.permission#CONNECTIVITY_INTERNAL}. 1535 * {@hide} 1536 */ 1537 public boolean requestNetworkTransitionWakelock(String forWhom) { 1538 try { 1539 mService.requestNetworkTransitionWakelock(forWhom); 1540 return true; 1541 } catch (RemoteException e) { 1542 return false; 1543 } 1544 } 1545 1546 /** 1547 * Report network connectivity status. This is currently used only 1548 * to alter status bar UI. 1549 * 1550 * @param networkType The type of network you want to report on 1551 * @param percentage The quality of the connection 0 is bad, 100 is good 1552 * 1553 * <p>This method requires the call to hold the permission 1554 * {@link android.Manifest.permission#STATUS_BAR}. 1555 * {@hide} 1556 */ 1557 public void reportInetCondition(int networkType, int percentage) { 1558 try { 1559 mService.reportInetCondition(networkType, percentage); 1560 } catch (RemoteException e) { 1561 } 1562 } 1563 1564 /** 1565 * Report a problem network to the framework. This provides a hint to the system 1566 * that there might be connectivity problems on this network and may cause 1567 * the framework to re-evaluate network connectivity and/or switch to another 1568 * network. 1569 * 1570 * @param network The {@link Network} the application was attempting to use 1571 * or {@code null} to indicate the current default network. 1572 */ 1573 public void reportBadNetwork(Network network) { 1574 try { 1575 mService.reportBadNetwork(network); 1576 } catch (RemoteException e) { 1577 } 1578 } 1579 1580 /** 1581 * Set a network-independent global http proxy. This is not normally what you want 1582 * for typical HTTP proxies - they are general network dependent. However if you're 1583 * doing something unusual like general internal filtering this may be useful. On 1584 * a private network where the proxy is not accessible, you may break HTTP using this. 1585 * 1586 * @param p The a {@link ProxyInfo} object defining the new global 1587 * HTTP proxy. A {@code null} value will clear the global HTTP proxy. 1588 * 1589 * <p>This method requires the call to hold the permission 1590 * android.Manifest.permission#CONNECTIVITY_INTERNAL. 1591 * @hide 1592 */ 1593 public void setGlobalProxy(ProxyInfo p) { 1594 try { 1595 mService.setGlobalProxy(p); 1596 } catch (RemoteException e) { 1597 } 1598 } 1599 1600 /** 1601 * Retrieve any network-independent global HTTP proxy. 1602 * 1603 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null} 1604 * if no global HTTP proxy is set. 1605 * 1606 * <p>This method requires the call to hold the permission 1607 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}. 1608 * @hide 1609 */ 1610 public ProxyInfo getGlobalProxy() { 1611 try { 1612 return mService.getGlobalProxy(); 1613 } catch (RemoteException e) { 1614 return null; 1615 } 1616 } 1617 1618 /** 1619 * Get the HTTP proxy settings for the current default network. Note that 1620 * if a global proxy is set, it will override any per-network setting. 1621 * 1622 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no 1623 * HTTP proxy is active. 1624 * 1625 * <p>This method requires the call to hold the permission 1626 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}. 1627 * {@hide} 1628 * @deprecated Deprecated in favor of {@link #getLinkProperties} 1629 */ 1630 public ProxyInfo getProxy() { 1631 try { 1632 return mService.getProxy(); 1633 } catch (RemoteException e) { 1634 return null; 1635 } 1636 } 1637 1638 /** 1639 * Sets a secondary requirement bit for the given networkType. 1640 * This requirement bit is generally under the control of the carrier 1641 * or its agents and is not directly controlled by the user. 1642 * 1643 * @param networkType The network who's dependence has changed 1644 * @param met Boolean - true if network use is OK, false if not 1645 * 1646 * <p>This method requires the call to hold the permission 1647 * {@link android.Manifest.permission#CONNECTIVITY_INTERNAL}. 1648 * {@hide} 1649 */ 1650 public void setDataDependency(int networkType, boolean met) { 1651 try { 1652 mService.setDataDependency(networkType, met); 1653 } catch (RemoteException e) { 1654 } 1655 } 1656 1657 /** 1658 * Returns true if the hardware supports the given network type 1659 * else it returns false. This doesn't indicate we have coverage 1660 * or are authorized onto a network, just whether or not the 1661 * hardware supports it. For example a GSM phone without a SIM 1662 * should still return {@code true} for mobile data, but a wifi only 1663 * tablet would return {@code false}. 1664 * 1665 * @param networkType The network type we'd like to check 1666 * @return {@code true} if supported, else {@code false} 1667 * 1668 * <p>This method requires the call to hold the permission 1669 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}. 1670 * @hide 1671 */ 1672 public boolean isNetworkSupported(int networkType) { 1673 try { 1674 return mService.isNetworkSupported(networkType); 1675 } catch (RemoteException e) {} 1676 return false; 1677 } 1678 1679 /** 1680 * Returns if the currently active data network is metered. A network is 1681 * classified as metered when the user is sensitive to heavy data usage on 1682 * that connection due to monetary costs, data limitations or 1683 * battery/performance issues. You should check this before doing large 1684 * data transfers, and warn the user or delay the operation until another 1685 * network is available. 1686 * 1687 * @return {@code true} if large transfers should be avoided, otherwise 1688 * {@code false}. 1689 * 1690 * <p>This method requires the call to hold the permission 1691 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}. 1692 */ 1693 public boolean isActiveNetworkMetered() { 1694 try { 1695 return mService.isActiveNetworkMetered(); 1696 } catch (RemoteException e) { 1697 return false; 1698 } 1699 } 1700 1701 /** 1702 * If the LockdownVpn mechanism is enabled, updates the vpn 1703 * with a reload of its profile. 1704 * 1705 * @return a boolean with {@code} indicating success 1706 * 1707 * <p>This method can only be called by the system UID 1708 * {@hide} 1709 */ 1710 public boolean updateLockdownVpn() { 1711 try { 1712 return mService.updateLockdownVpn(); 1713 } catch (RemoteException e) { 1714 return false; 1715 } 1716 } 1717 1718 /** 1719 * Signal that the captive portal check on the indicated network 1720 * is complete and whether its a captive portal or not. 1721 * 1722 * @param info the {@link NetworkInfo} object for the networkType 1723 * in question. 1724 * @param isCaptivePortal true/false. 1725 * 1726 * <p>This method requires the call to hold the permission 1727 * {@link android.Manifest.permission#CONNECTIVITY_INTERNAL}. 1728 * {@hide} 1729 */ 1730 public void captivePortalCheckCompleted(NetworkInfo info, boolean isCaptivePortal) { 1731 try { 1732 mService.captivePortalCheckCompleted(info, isCaptivePortal); 1733 } catch (RemoteException e) { 1734 } 1735 } 1736 1737 /** 1738 * Supply the backend messenger for a network tracker 1739 * 1740 * @param networkType NetworkType to set 1741 * @param messenger {@link Messenger} 1742 * {@hide} 1743 */ 1744 public void supplyMessenger(int networkType, Messenger messenger) { 1745 try { 1746 mService.supplyMessenger(networkType, messenger); 1747 } catch (RemoteException e) { 1748 } 1749 } 1750 1751 /** 1752 * Check mobile provisioning. 1753 * 1754 * @param suggestedTimeOutMs, timeout in milliseconds 1755 * 1756 * @return time out that will be used, maybe less that suggestedTimeOutMs 1757 * -1 if an error. 1758 * 1759 * {@hide} 1760 */ 1761 public int checkMobileProvisioning(int suggestedTimeOutMs) { 1762 int timeOutMs = -1; 1763 try { 1764 timeOutMs = mService.checkMobileProvisioning(suggestedTimeOutMs); 1765 } catch (RemoteException e) { 1766 } 1767 return timeOutMs; 1768 } 1769 1770 /** 1771 * Get the mobile provisioning url. 1772 * {@hide} 1773 */ 1774 public String getMobileProvisioningUrl() { 1775 try { 1776 return mService.getMobileProvisioningUrl(); 1777 } catch (RemoteException e) { 1778 } 1779 return null; 1780 } 1781 1782 /** 1783 * Get the mobile redirected provisioning url. 1784 * {@hide} 1785 */ 1786 public String getMobileRedirectedProvisioningUrl() { 1787 try { 1788 return mService.getMobileRedirectedProvisioningUrl(); 1789 } catch (RemoteException e) { 1790 } 1791 return null; 1792 } 1793 1794 /** 1795 * get the information about a specific network link 1796 * @hide 1797 */ 1798 public LinkQualityInfo getLinkQualityInfo(int networkType) { 1799 try { 1800 LinkQualityInfo li = mService.getLinkQualityInfo(networkType); 1801 return li; 1802 } catch (RemoteException e) { 1803 return null; 1804 } 1805 } 1806 1807 /** 1808 * get the information of currently active network link 1809 * @hide 1810 */ 1811 public LinkQualityInfo getActiveLinkQualityInfo() { 1812 try { 1813 LinkQualityInfo li = mService.getActiveLinkQualityInfo(); 1814 return li; 1815 } catch (RemoteException e) { 1816 return null; 1817 } 1818 } 1819 1820 /** 1821 * get the information of all network links 1822 * @hide 1823 */ 1824 public LinkQualityInfo[] getAllLinkQualityInfo() { 1825 try { 1826 LinkQualityInfo[] li = mService.getAllLinkQualityInfo(); 1827 return li; 1828 } catch (RemoteException e) { 1829 return null; 1830 } 1831 } 1832 1833 /** 1834 * Set sign in error notification to visible or in visible 1835 * 1836 * @param visible 1837 * @param networkType 1838 * 1839 * {@hide} 1840 */ 1841 public void setProvisioningNotificationVisible(boolean visible, int networkType, 1842 String extraInfo, String url) { 1843 try { 1844 mService.setProvisioningNotificationVisible(visible, networkType, extraInfo, url); 1845 } catch (RemoteException e) { 1846 } 1847 } 1848 1849 /** 1850 * Set the value for enabling/disabling airplane mode 1851 * 1852 * @param enable whether to enable airplane mode or not 1853 * 1854 * <p>This method requires the call to hold the permission 1855 * {@link android.Manifest.permission#CONNECTIVITY_INTERNAL}. 1856 * @hide 1857 */ 1858 public void setAirplaneMode(boolean enable) { 1859 try { 1860 mService.setAirplaneMode(enable); 1861 } catch (RemoteException e) { 1862 } 1863 } 1864 1865 /** {@hide} */ 1866 public void registerNetworkFactory(Messenger messenger, String name) { 1867 try { 1868 mService.registerNetworkFactory(messenger, name); 1869 } catch (RemoteException e) { } 1870 } 1871 1872 /** {@hide} */ 1873 public void unregisterNetworkFactory(Messenger messenger) { 1874 try { 1875 mService.unregisterNetworkFactory(messenger); 1876 } catch (RemoteException e) { } 1877 } 1878 1879 /** {@hide} */ 1880 public void registerNetworkAgent(Messenger messenger, NetworkInfo ni, LinkProperties lp, 1881 NetworkCapabilities nc, int score) { 1882 try { 1883 mService.registerNetworkAgent(messenger, ni, lp, nc, score); 1884 } catch (RemoteException e) { } 1885 } 1886 1887 /** 1888 * Base class for NetworkRequest callbacks. Used for notifications about network 1889 * changes. Should be extended by applications wanting notifications. 1890 */ 1891 public static class NetworkCallbackListener { 1892 /** @hide */ 1893 public static final int PRECHECK = 1; 1894 /** @hide */ 1895 public static final int AVAILABLE = 2; 1896 /** @hide */ 1897 public static final int LOSING = 3; 1898 /** @hide */ 1899 public static final int LOST = 4; 1900 /** @hide */ 1901 public static final int UNAVAIL = 5; 1902 /** @hide */ 1903 public static final int CAP_CHANGED = 6; 1904 /** @hide */ 1905 public static final int PROP_CHANGED = 7; 1906 /** @hide */ 1907 public static final int CANCELED = 8; 1908 1909 /** 1910 * @hide 1911 * Called whenever the framework connects to a network that it may use to 1912 * satisfy this request 1913 */ 1914 public void onPreCheck(NetworkRequest networkRequest, Network network) {} 1915 1916 /** 1917 * Called when the framework connects and has declared new network ready for use. 1918 * 1919 * @param networkRequest The {@link NetworkRequest} used to initiate the request. 1920 * @param network The {@link Network} of the satisfying network. 1921 */ 1922 public void onAvailable(NetworkRequest networkRequest, Network network) {} 1923 1924 /** 1925 * Called when the network is about to be disconnected. Often paired with an 1926 * {@link NetworkCallbackListener#onAvailable} call with the new replacement network 1927 * for graceful handover. This may not be called if we have a hard loss 1928 * (loss without warning). This may be followed by either a 1929 * {@link NetworkCallbackListener#onLost} call or a 1930 * {@link NetworkCallbackListener#onAvailable} call for this network depending 1931 * on whether we lose or regain it. 1932 * 1933 * @param networkRequest The {@link NetworkRequest} used to initiate the request. 1934 * @param network The {@link Network} of the failing network. 1935 * @param maxSecToLive The time in seconds the framework will attempt to keep the 1936 * network connected. Note that the network may suffers a 1937 * hard loss at any time. 1938 */ 1939 public void onLosing(NetworkRequest networkRequest, Network network, int maxSecToLive) {} 1940 1941 /** 1942 * Called when the framework has a hard loss of the network or when the 1943 * graceful failure ends. 1944 * 1945 * @param networkRequest The {@link NetworkRequest} used to initiate the request. 1946 * @param network The {@link Network} lost. 1947 */ 1948 public void onLost(NetworkRequest networkRequest, Network network) {} 1949 1950 /** 1951 * Called if no network is found in the given timeout time. If no timeout is given, 1952 * this will not be called. 1953 * @hide 1954 */ 1955 public void onUnavailable(NetworkRequest networkRequest) {} 1956 1957 /** 1958 * Called when the network the framework connected to for this request 1959 * changes capabilities but still satisfies the stated need. 1960 * 1961 * @param networkRequest The {@link NetworkRequest} used to initiate the request. 1962 * @param network The {@link Network} whose capabilities have changed. 1963 * @param networkCapabilities The new {@link NetworkCapabilities} for this network. 1964 */ 1965 public void onNetworkCapabilitiesChanged(NetworkRequest networkRequest, Network network, 1966 NetworkCapabilities networkCapabilities) {} 1967 1968 /** 1969 * Called when the network the framework connected to for this request 1970 * changes {@link LinkProperties}. 1971 * 1972 * @param networkRequest The {@link NetworkRequest} used to initiate the request. 1973 * @param network The {@link Network} whose link properties have changed. 1974 * @param linkProperties The new {@link LinkProperties} for this network. 1975 */ 1976 public void onLinkPropertiesChanged(NetworkRequest networkRequest, Network network, 1977 LinkProperties linkProperties) {} 1978 1979 /** 1980 * Called when a {@link #releaseNetworkRequest} call concludes and the registered 1981 * callbacks will no longer be used. 1982 * 1983 * @param networkRequest The {@link NetworkRequest} used to initiate the request. 1984 */ 1985 public void onReleased(NetworkRequest networkRequest) {} 1986 } 1987 1988 private static final int BASE = Protocol.BASE_CONNECTIVITY_MANAGER; 1989 /** @hide obj = pair(NetworkRequest, Network) */ 1990 public static final int CALLBACK_PRECHECK = BASE + 1; 1991 /** @hide obj = pair(NetworkRequest, Network) */ 1992 public static final int CALLBACK_AVAILABLE = BASE + 2; 1993 /** @hide obj = pair(NetworkRequest, Network), arg1 = ttl */ 1994 public static final int CALLBACK_LOSING = BASE + 3; 1995 /** @hide obj = pair(NetworkRequest, Network) */ 1996 public static final int CALLBACK_LOST = BASE + 4; 1997 /** @hide obj = NetworkRequest */ 1998 public static final int CALLBACK_UNAVAIL = BASE + 5; 1999 /** @hide obj = pair(NetworkRequest, Network) */ 2000 public static final int CALLBACK_CAP_CHANGED = BASE + 6; 2001 /** @hide obj = pair(NetworkRequest, Network) */ 2002 public static final int CALLBACK_IP_CHANGED = BASE + 7; 2003 /** @hide obj = NetworkRequest */ 2004 public static final int CALLBACK_RELEASED = BASE + 8; 2005 /** @hide */ 2006 public static final int CALLBACK_EXIT = BASE + 9; 2007 /** @hide obj = NetworkCapabilities, arg1 = seq number */ 2008 private static final int EXPIRE_LEGACY_REQUEST = BASE + 10; 2009 2010 private class CallbackHandler extends Handler { 2011 private final HashMap<NetworkRequest, NetworkCallbackListener>mCallbackMap; 2012 private final AtomicInteger mRefCount; 2013 private static final String TAG = "ConnectivityManager.CallbackHandler"; 2014 private final ConnectivityManager mCm; 2015 2016 CallbackHandler(Looper looper, HashMap<NetworkRequest, NetworkCallbackListener>callbackMap, 2017 AtomicInteger refCount, ConnectivityManager cm) { 2018 super(looper); 2019 mCallbackMap = callbackMap; 2020 mRefCount = refCount; 2021 mCm = cm; 2022 } 2023 2024 @Override 2025 public void handleMessage(Message message) { 2026 Log.d(TAG, "CM callback handler got msg " + message.what); 2027 switch (message.what) { 2028 case CALLBACK_PRECHECK: { 2029 NetworkRequest request = getNetworkRequest(message); 2030 NetworkCallbackListener callbacks = getCallbacks(request); 2031 if (callbacks != null) { 2032 callbacks.onPreCheck(request, getNetwork(message)); 2033 } else { 2034 Log.e(TAG, "callback not found for PRECHECK message"); 2035 } 2036 break; 2037 } 2038 case CALLBACK_AVAILABLE: { 2039 NetworkRequest request = getNetworkRequest(message); 2040 NetworkCallbackListener callbacks = getCallbacks(request); 2041 if (callbacks != null) { 2042 callbacks.onAvailable(request, getNetwork(message)); 2043 } else { 2044 Log.e(TAG, "callback not found for AVAILABLE message"); 2045 } 2046 break; 2047 } 2048 case CALLBACK_LOSING: { 2049 NetworkRequest request = getNetworkRequest(message); 2050 NetworkCallbackListener callbacks = getCallbacks(request); 2051 if (callbacks != null) { 2052 callbacks.onLosing(request, getNetwork(message), message.arg1); 2053 } else { 2054 Log.e(TAG, "callback not found for LOSING message"); 2055 } 2056 break; 2057 } 2058 case CALLBACK_LOST: { 2059 NetworkRequest request = getNetworkRequest(message); 2060 NetworkCallbackListener callbacks = getCallbacks(request); 2061 if (callbacks != null) { 2062 callbacks.onLost(request, getNetwork(message)); 2063 } else { 2064 Log.e(TAG, "callback not found for LOST message"); 2065 } 2066 break; 2067 } 2068 case CALLBACK_UNAVAIL: { 2069 NetworkRequest req = (NetworkRequest)message.obj; 2070 NetworkCallbackListener callbacks = null; 2071 synchronized(mCallbackMap) { 2072 callbacks = mCallbackMap.get(req); 2073 } 2074 if (callbacks != null) { 2075 callbacks.onUnavailable(req); 2076 } else { 2077 Log.e(TAG, "callback not found for UNAVAIL message"); 2078 } 2079 break; 2080 } 2081 case CALLBACK_CAP_CHANGED: { 2082 NetworkRequest request = getNetworkRequest(message); 2083 NetworkCallbackListener callbacks = getCallbacks(request); 2084 if (callbacks != null) { 2085 Network network = getNetwork(message); 2086 NetworkCapabilities cap = mCm.getNetworkCapabilities(network); 2087 2088 callbacks.onNetworkCapabilitiesChanged(request, network, cap); 2089 } else { 2090 Log.e(TAG, "callback not found for CHANGED message"); 2091 } 2092 break; 2093 } 2094 case CALLBACK_IP_CHANGED: { 2095 NetworkRequest request = getNetworkRequest(message); 2096 NetworkCallbackListener callbacks = getCallbacks(request); 2097 if (callbacks != null) { 2098 Network network = getNetwork(message); 2099 LinkProperties lp = mCm.getLinkProperties(network); 2100 2101 callbacks.onLinkPropertiesChanged(request, network, lp); 2102 } else { 2103 Log.e(TAG, "callback not found for CHANGED message"); 2104 } 2105 break; 2106 } 2107 case CALLBACK_RELEASED: { 2108 NetworkRequest req = (NetworkRequest)message.obj; 2109 NetworkCallbackListener callbacks = null; 2110 synchronized(mCallbackMap) { 2111 callbacks = mCallbackMap.remove(req); 2112 } 2113 if (callbacks != null) { 2114 callbacks.onReleased(req); 2115 } else { 2116 Log.e(TAG, "callback not found for CANCELED message"); 2117 } 2118 synchronized(mRefCount) { 2119 if (mRefCount.decrementAndGet() == 0) { 2120 getLooper().quit(); 2121 } 2122 } 2123 break; 2124 } 2125 case CALLBACK_EXIT: { 2126 Log.d(TAG, "Listener quiting"); 2127 getLooper().quit(); 2128 break; 2129 } 2130 case EXPIRE_LEGACY_REQUEST: { 2131 expireRequest((NetworkCapabilities)message.obj, message.arg1); 2132 break; 2133 } 2134 } 2135 } 2136 2137 private NetworkRequest getNetworkRequest(Message msg) { 2138 return (NetworkRequest)(msg.obj); 2139 } 2140 private NetworkCallbackListener getCallbacks(NetworkRequest req) { 2141 synchronized(mCallbackMap) { 2142 return mCallbackMap.get(req); 2143 } 2144 } 2145 private Network getNetwork(Message msg) { 2146 return new Network(msg.arg2); 2147 } 2148 private NetworkCallbackListener removeCallbacks(Message msg) { 2149 NetworkRequest req = (NetworkRequest)msg.obj; 2150 synchronized(mCallbackMap) { 2151 return mCallbackMap.remove(req); 2152 } 2153 } 2154 } 2155 2156 private void addCallbackListener() { 2157 synchronized(sCallbackRefCount) { 2158 if (sCallbackRefCount.incrementAndGet() == 1) { 2159 // TODO - switch this over to a ManagerThread or expire it when done 2160 HandlerThread callbackThread = new HandlerThread("ConnectivityManager"); 2161 callbackThread.start(); 2162 sCallbackHandler = new CallbackHandler(callbackThread.getLooper(), 2163 sNetworkCallbackListener, sCallbackRefCount, this); 2164 } 2165 } 2166 } 2167 2168 private void removeCallbackListener() { 2169 synchronized(sCallbackRefCount) { 2170 if (sCallbackRefCount.decrementAndGet() == 0) { 2171 sCallbackHandler.obtainMessage(CALLBACK_EXIT).sendToTarget(); 2172 sCallbackHandler = null; 2173 } 2174 } 2175 } 2176 2177 static final HashMap<NetworkRequest, NetworkCallbackListener> sNetworkCallbackListener = 2178 new HashMap<NetworkRequest, NetworkCallbackListener>(); 2179 static final AtomicInteger sCallbackRefCount = new AtomicInteger(0); 2180 static CallbackHandler sCallbackHandler = null; 2181 2182 private final static int LISTEN = 1; 2183 private final static int REQUEST = 2; 2184 2185 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, 2186 NetworkCallbackListener networkCallbackListener, int timeoutSec, int action, 2187 int legacyType) { 2188 NetworkRequest networkRequest = null; 2189 if (networkCallbackListener == null) { 2190 throw new IllegalArgumentException("null NetworkCallbackListener"); 2191 } 2192 if (need == null) throw new IllegalArgumentException("null NetworkCapabilities"); 2193 try { 2194 addCallbackListener(); 2195 if (action == LISTEN) { 2196 networkRequest = mService.listenForNetwork(need, new Messenger(sCallbackHandler), 2197 new Binder()); 2198 } else { 2199 networkRequest = mService.requestNetwork(need, new Messenger(sCallbackHandler), 2200 timeoutSec, new Binder(), legacyType); 2201 } 2202 if (networkRequest != null) { 2203 synchronized(sNetworkCallbackListener) { 2204 sNetworkCallbackListener.put(networkRequest, networkCallbackListener); 2205 } 2206 } 2207 } catch (RemoteException e) {} 2208 if (networkRequest == null) removeCallbackListener(); 2209 return networkRequest; 2210 } 2211 2212 /** 2213 * Request a network to satisfy a set of {@link NetworkCapabilities}. 2214 * 2215 * This {@link NetworkRequest} will live until released via 2216 * {@link #releaseNetworkRequest} or the calling application exits. 2217 * Status of the request can be followed by listening to the various 2218 * callbacks described in {@link NetworkCallbackListener}. The {@link Network} 2219 * can be used to direct traffic to the network. 2220 * 2221 * @param need {@link NetworkCapabilities} required by this request. 2222 * @param networkCallbackListener The {@link NetworkCallbackListener} to be utilized for this 2223 * request. Note the callbacks can be shared by multiple 2224 * requests and the NetworkRequest token utilized to 2225 * determine to which request the callback relates. 2226 * @return A {@link NetworkRequest} object identifying the request. 2227 */ 2228 public NetworkRequest requestNetwork(NetworkCapabilities need, 2229 NetworkCallbackListener networkCallbackListener) { 2230 return sendRequestForNetwork(need, networkCallbackListener, 0, REQUEST, TYPE_NONE); 2231 } 2232 2233 /** 2234 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited 2235 * by a timeout. 2236 * 2237 * This function behaves identically to the non-timedout version, but if a suitable 2238 * network is not found within the given time (in Seconds) the 2239 * {@link NetworkCallbackListener#unavailable} callback is called. The request must 2240 * still be released normally by calling {@link releaseNetworkRequest}. 2241 * @param need {@link NetworkCapabilities} required by this request. 2242 * @param networkCallbackListener The callbacks to be utilized for this request. Note 2243 * the callbacks can be shared by multiple requests and 2244 * the NetworkRequest token utilized to determine to which 2245 * request the callback relates. 2246 * @param timeoutSec The time in seconds to attempt looking for a suitable network 2247 * before {@link NetworkCallbackListener#unavailable} is called. 2248 * @return A {@link NetworkRequest} object identifying the request. 2249 * @hide 2250 */ 2251 public NetworkRequest requestNetwork(NetworkCapabilities need, 2252 NetworkCallbackListener networkCallbackListener, int timeoutSec) { 2253 return sendRequestForNetwork(need, networkCallbackListener, timeoutSec, REQUEST, 2254 TYPE_NONE); 2255 } 2256 2257 /** 2258 * The maximum number of seconds the framework will look for a suitable network 2259 * during a timeout-equiped call to {@link requestNetwork}. 2260 * {@hide} 2261 */ 2262 public final static int MAX_NETWORK_REQUEST_TIMEOUT_SEC = 100 * 60; 2263 2264 /** 2265 * The lookup key for a {@link Network} object included with the intent after 2266 * succesfully finding a network for the applications request. Retrieve it with 2267 * {@link android.content.Intent#getParcelableExtra(String)}. 2268 */ 2269 public static final String EXTRA_NETWORK_REQUEST_NETWORK = "networkRequestNetwork"; 2270 2271 /** 2272 * The lookup key for a {@link NetworkCapabilities} object included with the intent after 2273 * succesfully finding a network for the applications request. Retrieve it with 2274 * {@link android.content.Intent#getParcelableExtra(String)}. 2275 */ 2276 public static final String EXTRA_NETWORK_REQUEST_NETWORK_CAPABILITIES = 2277 "networkRequestNetworkCapabilities"; 2278 2279 2280 /** 2281 * Request a network to satisfy a set of {@link NetworkCapabilities}. 2282 * 2283 * This function behavies identically to the callback-equiped version, but instead 2284 * of {@link NetworkCallbackListener} a {@link PendingIntent} is used. This means 2285 * the request may outlive the calling application and get called back when a suitable 2286 * network is found. 2287 * <p> 2288 * The operation is an Intent broadcast that goes to a broadcast receiver that 2289 * you registered with {@link Context#registerReceiver} or through the 2290 * <receiver> tag in an AndroidManifest.xml file 2291 * <p> 2292 * The operation Intent is delivered with two extras, a {@link Network} typed 2293 * extra called {@link #EXTRA_NETWORK_REQUEST_NETWORK} and a {@link NetworkCapabilities} 2294 * typed extra called {@link #EXTRA_NETWORK_REQUEST_NETWORK_CAPABILITIES} containing 2295 * the original requests parameters. It is important to create a new, 2296 * {@link NetworkCallbackListener} based request before completing the processing of the 2297 * Intent to reserve the network or it will be released shortly after the Intent 2298 * is processed. 2299 * <p> 2300 * If there is already an request for this Intent registered (with the equality of 2301 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and 2302 * replaced by this one, effectively releasing the previous {@link NetworkRequest}. 2303 * <p> 2304 * The request may be released normally by calling {@link #releaseNetworkRequest}. 2305 * 2306 * @param need {@link NetworkCapabilities} required by this request. 2307 * @param operation Action to perform when the network is available (corresponds 2308 * to the {@link NetworkCallbackListener#onAvailable} call. Typically 2309 * comes from {@link PendingIntent#getBroadcast}. 2310 * @return A {@link NetworkRequest} object identifying the request. 2311 */ 2312 public NetworkRequest requestNetwork(NetworkCapabilities need, PendingIntent operation) { 2313 try { 2314 return mService.pendingRequestForNetwork(need, operation); 2315 } catch (RemoteException e) {} 2316 return null; 2317 } 2318 2319 /** 2320 * Registers to receive notifications about all networks which satisfy the given 2321 * {@link NetworkCapabilities}. The callbacks will continue to be called until 2322 * either the application exits or the request is released using 2323 * {@link #releaseNetworkRequest}. 2324 * 2325 * @param need {@link NetworkCapabilities} required by this request. 2326 * @param networkCallbackListener The {@link NetworkCallbackListener} to be called as suitable 2327 * networks change state. 2328 * @return A {@link NetworkRequest} object identifying the request. 2329 */ 2330 public NetworkRequest listenForNetwork(NetworkCapabilities need, 2331 NetworkCallbackListener networkCallbackListener) { 2332 return sendRequestForNetwork(need, networkCallbackListener, 0, LISTEN, TYPE_NONE); 2333 } 2334 2335 /** 2336 * Releases a {@link NetworkRequest} generated either through a {@link #requestNetwork} 2337 * or a {@link #listenForNetwork} call. The {@link NetworkCallbackListener} given in the 2338 * earlier call may continue receiving calls until the 2339 * {@link NetworkCallbackListener#onReleased} function is called, signifying the end 2340 * of the request. 2341 * 2342 * @param networkRequest The {@link NetworkRequest} generated by an earlier call to 2343 * {@link #requestNetwork} or {@link #listenForNetwork}. 2344 */ 2345 public void releaseNetworkRequest(NetworkRequest networkRequest) { 2346 if (networkRequest == null) throw new IllegalArgumentException("null NetworkRequest"); 2347 try { 2348 mService.releaseNetworkRequest(networkRequest); 2349 } catch (RemoteException e) {} 2350 } 2351} 2352