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