ConnectivityManager.java revision c91b5348a56f79b4ff5f42a7689dd036ecfd7149
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 /** 1406 * Get the set of tetherable, available interfaces. This list is limited by 1407 * device configuration and current interface existence. 1408 * 1409 * @return an array of 0 or more Strings of tetherable interface names. 1410 * 1411 * <p>This method requires the call to hold the permission 1412 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}. 1413 * {@hide} 1414 */ 1415 public String[] getTetherableIfaces() { 1416 try { 1417 return mService.getTetherableIfaces(); 1418 } catch (RemoteException e) { 1419 return new String[0]; 1420 } 1421 } 1422 1423 /** 1424 * Get the set of tethered interfaces. 1425 * 1426 * @return an array of 0 or more String of currently tethered interface names. 1427 * 1428 * <p>This method requires the call to hold the permission 1429 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}. 1430 * {@hide} 1431 */ 1432 public String[] getTetheredIfaces() { 1433 try { 1434 return mService.getTetheredIfaces(); 1435 } catch (RemoteException e) { 1436 return new String[0]; 1437 } 1438 } 1439 1440 /** 1441 * Get the set of interface names which attempted to tether but 1442 * failed. Re-attempting to tether may cause them to reset to the Tethered 1443 * state. Alternatively, causing the interface to be destroyed and recreated 1444 * may cause them to reset to the available state. 1445 * {@link ConnectivityManager#getLastTetherError} can be used to get more 1446 * information on the cause of the errors. 1447 * 1448 * @return an array of 0 or more String indicating the interface names 1449 * which failed to tether. 1450 * 1451 * <p>This method requires the call to hold the permission 1452 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}. 1453 * {@hide} 1454 */ 1455 public String[] getTetheringErroredIfaces() { 1456 try { 1457 return mService.getTetheringErroredIfaces(); 1458 } catch (RemoteException e) { 1459 return new String[0]; 1460 } 1461 } 1462 1463 /** 1464 * Get the set of tethered dhcp ranges. 1465 * 1466 * @return an array of 0 or more {@code String} of tethered dhcp ranges. 1467 * {@hide} 1468 */ 1469 public String[] getTetheredDhcpRanges() { 1470 try { 1471 return mService.getTetheredDhcpRanges(); 1472 } catch (RemoteException e) { 1473 return new String[0]; 1474 } 1475 } 1476 1477 /** 1478 * Attempt to tether the named interface. This will setup a dhcp server 1479 * on the interface, forward and NAT IP packets and forward DNS requests 1480 * to the best active upstream network interface. Note that if no upstream 1481 * IP network interface is available, dhcp will still run and traffic will be 1482 * allowed between the tethered devices and this device, though upstream net 1483 * access will of course fail until an upstream network interface becomes 1484 * active. 1485 * 1486 * @param iface the interface name to tether. 1487 * @return error a {@code TETHER_ERROR} value indicating success or failure type 1488 * 1489 * <p>This method requires the call to hold the permission 1490 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE}. 1491 * {@hide} 1492 */ 1493 public int tether(String iface) { 1494 try { 1495 return mService.tether(iface); 1496 } catch (RemoteException e) { 1497 return TETHER_ERROR_SERVICE_UNAVAIL; 1498 } 1499 } 1500 1501 /** 1502 * Stop tethering the named interface. 1503 * 1504 * @param iface the interface name to untether. 1505 * @return error a {@code TETHER_ERROR} value indicating success or failure type 1506 * 1507 * <p>This method requires the call to hold the permission 1508 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE}. 1509 * {@hide} 1510 */ 1511 public int untether(String iface) { 1512 try { 1513 return mService.untether(iface); 1514 } catch (RemoteException e) { 1515 return TETHER_ERROR_SERVICE_UNAVAIL; 1516 } 1517 } 1518 1519 /** 1520 * Check if the device allows for tethering. It may be disabled via 1521 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or 1522 * due to device configuration. 1523 * 1524 * @return a boolean - {@code true} indicating Tethering is supported. 1525 * 1526 * <p>This method requires the call to hold the permission 1527 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}. 1528 * {@hide} 1529 */ 1530 public boolean isTetheringSupported() { 1531 try { 1532 return mService.isTetheringSupported(); 1533 } catch (RemoteException e) { 1534 return false; 1535 } 1536 } 1537 1538 /** 1539 * Get the list of regular expressions that define any tetherable 1540 * USB network interfaces. If USB tethering is not supported by the 1541 * device, this list should be empty. 1542 * 1543 * @return an array of 0 or more regular expression Strings defining 1544 * what interfaces are considered tetherable usb interfaces. 1545 * 1546 * <p>This method requires the call to hold the permission 1547 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}. 1548 * {@hide} 1549 */ 1550 public String[] getTetherableUsbRegexs() { 1551 try { 1552 return mService.getTetherableUsbRegexs(); 1553 } catch (RemoteException e) { 1554 return new String[0]; 1555 } 1556 } 1557 1558 /** 1559 * Get the list of regular expressions that define any tetherable 1560 * Wifi network interfaces. If Wifi tethering is not supported by the 1561 * device, this list should be empty. 1562 * 1563 * @return an array of 0 or more regular expression Strings defining 1564 * what interfaces are considered tetherable wifi interfaces. 1565 * 1566 * <p>This method requires the call to hold the permission 1567 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}. 1568 * {@hide} 1569 */ 1570 public String[] getTetherableWifiRegexs() { 1571 try { 1572 return mService.getTetherableWifiRegexs(); 1573 } catch (RemoteException e) { 1574 return new String[0]; 1575 } 1576 } 1577 1578 /** 1579 * Get the list of regular expressions that define any tetherable 1580 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the 1581 * device, this list should be empty. 1582 * 1583 * @return an array of 0 or more regular expression Strings defining 1584 * what interfaces are considered tetherable bluetooth interfaces. 1585 * 1586 * <p>This method requires the call to hold the permission 1587 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}. 1588 * {@hide} 1589 */ 1590 public String[] getTetherableBluetoothRegexs() { 1591 try { 1592 return mService.getTetherableBluetoothRegexs(); 1593 } catch (RemoteException e) { 1594 return new String[0]; 1595 } 1596 } 1597 1598 /** 1599 * Attempt to both alter the mode of USB and Tethering of USB. A 1600 * utility method to deal with some of the complexity of USB - will 1601 * attempt to switch to Rndis and subsequently tether the resulting 1602 * interface on {@code true} or turn off tethering and switch off 1603 * Rndis on {@code false}. 1604 * 1605 * @param enable a boolean - {@code true} to enable tethering 1606 * @return error a {@code TETHER_ERROR} value indicating success or failure type 1607 * 1608 * <p>This method requires the call to hold the permission 1609 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE}. 1610 * {@hide} 1611 */ 1612 public int setUsbTethering(boolean enable) { 1613 try { 1614 return mService.setUsbTethering(enable); 1615 } catch (RemoteException e) { 1616 return TETHER_ERROR_SERVICE_UNAVAIL; 1617 } 1618 } 1619 1620 /** {@hide} */ 1621 public static final int TETHER_ERROR_NO_ERROR = 0; 1622 /** {@hide} */ 1623 public static final int TETHER_ERROR_UNKNOWN_IFACE = 1; 1624 /** {@hide} */ 1625 public static final int TETHER_ERROR_SERVICE_UNAVAIL = 2; 1626 /** {@hide} */ 1627 public static final int TETHER_ERROR_UNSUPPORTED = 3; 1628 /** {@hide} */ 1629 public static final int TETHER_ERROR_UNAVAIL_IFACE = 4; 1630 /** {@hide} */ 1631 public static final int TETHER_ERROR_MASTER_ERROR = 5; 1632 /** {@hide} */ 1633 public static final int TETHER_ERROR_TETHER_IFACE_ERROR = 6; 1634 /** {@hide} */ 1635 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR = 7; 1636 /** {@hide} */ 1637 public static final int TETHER_ERROR_ENABLE_NAT_ERROR = 8; 1638 /** {@hide} */ 1639 public static final int TETHER_ERROR_DISABLE_NAT_ERROR = 9; 1640 /** {@hide} */ 1641 public static final int TETHER_ERROR_IFACE_CFG_ERROR = 10; 1642 1643 /** 1644 * Get a more detailed error code after a Tethering or Untethering 1645 * request asynchronously failed. 1646 * 1647 * @param iface The name of the interface of interest 1648 * @return error The error code of the last error tethering or untethering the named 1649 * interface 1650 * 1651 * <p>This method requires the call to hold the permission 1652 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}. 1653 * {@hide} 1654 */ 1655 public int getLastTetherError(String iface) { 1656 try { 1657 return mService.getLastTetherError(iface); 1658 } catch (RemoteException e) { 1659 return TETHER_ERROR_SERVICE_UNAVAIL; 1660 } 1661 } 1662 1663 /** 1664 * Report network connectivity status. This is currently used only 1665 * to alter status bar UI. 1666 * 1667 * @param networkType The type of network you want to report on 1668 * @param percentage The quality of the connection 0 is bad, 100 is good 1669 * 1670 * <p>This method requires the call to hold the permission 1671 * {@link android.Manifest.permission#STATUS_BAR}. 1672 * {@hide} 1673 */ 1674 public void reportInetCondition(int networkType, int percentage) { 1675 try { 1676 mService.reportInetCondition(networkType, percentage); 1677 } catch (RemoteException e) { 1678 } 1679 } 1680 1681 /** 1682 * Report a problem network to the framework. This provides a hint to the system 1683 * that there might be connectivity problems on this network and may cause 1684 * the framework to re-evaluate network connectivity and/or switch to another 1685 * network. 1686 * 1687 * @param network The {@link Network} the application was attempting to use 1688 * or {@code null} to indicate the current default network. 1689 */ 1690 public void reportBadNetwork(Network network) { 1691 try { 1692 mService.reportBadNetwork(network); 1693 } catch (RemoteException e) { 1694 } 1695 } 1696 1697 /** 1698 * Set a network-independent global http proxy. This is not normally what you want 1699 * for typical HTTP proxies - they are general network dependent. However if you're 1700 * doing something unusual like general internal filtering this may be useful. On 1701 * a private network where the proxy is not accessible, you may break HTTP using this. 1702 * 1703 * @param p The a {@link ProxyInfo} object defining the new global 1704 * HTTP proxy. A {@code null} value will clear the global HTTP proxy. 1705 * 1706 * <p>This method requires the call to hold the permission 1707 * android.Manifest.permission#CONNECTIVITY_INTERNAL. 1708 * @hide 1709 */ 1710 public void setGlobalProxy(ProxyInfo p) { 1711 try { 1712 mService.setGlobalProxy(p); 1713 } catch (RemoteException e) { 1714 } 1715 } 1716 1717 /** 1718 * Retrieve any network-independent global HTTP proxy. 1719 * 1720 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null} 1721 * if no global HTTP proxy is set. 1722 * 1723 * <p>This method requires the call to hold the permission 1724 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}. 1725 * @hide 1726 */ 1727 public ProxyInfo getGlobalProxy() { 1728 try { 1729 return mService.getGlobalProxy(); 1730 } catch (RemoteException e) { 1731 return null; 1732 } 1733 } 1734 1735 /** 1736 * Get the HTTP proxy settings for the current default network. Note that 1737 * if a global proxy is set, it will override any per-network setting. 1738 * 1739 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no 1740 * HTTP proxy is active. 1741 * 1742 * <p>This method requires the call to hold the permission 1743 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}. 1744 * {@hide} 1745 * @deprecated Deprecated in favor of {@link #getLinkProperties} 1746 */ 1747 public ProxyInfo getProxy() { 1748 try { 1749 return mService.getProxy(); 1750 } catch (RemoteException e) { 1751 return null; 1752 } 1753 } 1754 1755 /** 1756 * Sets a secondary requirement bit for the given networkType. 1757 * This requirement bit is generally under the control of the carrier 1758 * or its agents and is not directly controlled by the user. 1759 * 1760 * @param networkType The network who's dependence has changed 1761 * @param met Boolean - true if network use is OK, false if not 1762 * 1763 * <p>This method requires the call to hold the permission 1764 * {@link android.Manifest.permission#CONNECTIVITY_INTERNAL}. 1765 * {@hide} 1766 */ 1767 public void setDataDependency(int networkType, boolean met) { 1768 try { 1769 mService.setDataDependency(networkType, met); 1770 } catch (RemoteException e) { 1771 } 1772 } 1773 1774 /** 1775 * Returns true if the hardware supports the given network type 1776 * else it returns false. This doesn't indicate we have coverage 1777 * or are authorized onto a network, just whether or not the 1778 * hardware supports it. For example a GSM phone without a SIM 1779 * should still return {@code true} for mobile data, but a wifi only 1780 * tablet would return {@code false}. 1781 * 1782 * @param networkType The network type we'd like to check 1783 * @return {@code true} if supported, else {@code false} 1784 * 1785 * <p>This method requires the call to hold the permission 1786 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}. 1787 * @hide 1788 */ 1789 public boolean isNetworkSupported(int networkType) { 1790 try { 1791 return mService.isNetworkSupported(networkType); 1792 } catch (RemoteException e) {} 1793 return false; 1794 } 1795 1796 /** 1797 * Returns if the currently active data network is metered. A network is 1798 * classified as metered when the user is sensitive to heavy data usage on 1799 * that connection due to monetary costs, data limitations or 1800 * battery/performance issues. You should check this before doing large 1801 * data transfers, and warn the user or delay the operation until another 1802 * network is available. 1803 * 1804 * @return {@code true} if large transfers should be avoided, otherwise 1805 * {@code false}. 1806 * 1807 * <p>This method requires the call to hold the permission 1808 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}. 1809 */ 1810 public boolean isActiveNetworkMetered() { 1811 try { 1812 return mService.isActiveNetworkMetered(); 1813 } catch (RemoteException e) { 1814 return false; 1815 } 1816 } 1817 1818 /** 1819 * If the LockdownVpn mechanism is enabled, updates the vpn 1820 * with a reload of its profile. 1821 * 1822 * @return a boolean with {@code} indicating success 1823 * 1824 * <p>This method can only be called by the system UID 1825 * {@hide} 1826 */ 1827 public boolean updateLockdownVpn() { 1828 try { 1829 return mService.updateLockdownVpn(); 1830 } catch (RemoteException e) { 1831 return false; 1832 } 1833 } 1834 1835 /** 1836 * Signal that the captive portal check on the indicated network 1837 * is complete and whether its a captive portal or not. 1838 * 1839 * @param info the {@link NetworkInfo} object for the networkType 1840 * in question. 1841 * @param isCaptivePortal true/false. 1842 * 1843 * <p>This method requires the call to hold the permission 1844 * {@link android.Manifest.permission#CONNECTIVITY_INTERNAL}. 1845 * {@hide} 1846 */ 1847 public void captivePortalCheckCompleted(NetworkInfo info, boolean isCaptivePortal) { 1848 try { 1849 mService.captivePortalCheckCompleted(info, isCaptivePortal); 1850 } catch (RemoteException e) { 1851 } 1852 } 1853 1854 /** 1855 * Supply the backend messenger for a network tracker 1856 * 1857 * @param networkType NetworkType to set 1858 * @param messenger {@link Messenger} 1859 * {@hide} 1860 */ 1861 public void supplyMessenger(int networkType, Messenger messenger) { 1862 try { 1863 mService.supplyMessenger(networkType, messenger); 1864 } catch (RemoteException e) { 1865 } 1866 } 1867 1868 /** 1869 * Check mobile provisioning. 1870 * 1871 * @param suggestedTimeOutMs, timeout in milliseconds 1872 * 1873 * @return time out that will be used, maybe less that suggestedTimeOutMs 1874 * -1 if an error. 1875 * 1876 * {@hide} 1877 */ 1878 public int checkMobileProvisioning(int suggestedTimeOutMs) { 1879 int timeOutMs = -1; 1880 try { 1881 timeOutMs = mService.checkMobileProvisioning(suggestedTimeOutMs); 1882 } catch (RemoteException e) { 1883 } 1884 return timeOutMs; 1885 } 1886 1887 /** 1888 * Get the mobile provisioning url. 1889 * {@hide} 1890 */ 1891 public String getMobileProvisioningUrl() { 1892 try { 1893 return mService.getMobileProvisioningUrl(); 1894 } catch (RemoteException e) { 1895 } 1896 return null; 1897 } 1898 1899 /** 1900 * Get the mobile redirected provisioning url. 1901 * {@hide} 1902 */ 1903 public String getMobileRedirectedProvisioningUrl() { 1904 try { 1905 return mService.getMobileRedirectedProvisioningUrl(); 1906 } catch (RemoteException e) { 1907 } 1908 return null; 1909 } 1910 1911 /** 1912 * get the information about a specific network link 1913 * @hide 1914 */ 1915 public LinkQualityInfo getLinkQualityInfo(int networkType) { 1916 try { 1917 LinkQualityInfo li = mService.getLinkQualityInfo(networkType); 1918 return li; 1919 } catch (RemoteException e) { 1920 return null; 1921 } 1922 } 1923 1924 /** 1925 * get the information of currently active network link 1926 * @hide 1927 */ 1928 public LinkQualityInfo getActiveLinkQualityInfo() { 1929 try { 1930 LinkQualityInfo li = mService.getActiveLinkQualityInfo(); 1931 return li; 1932 } catch (RemoteException e) { 1933 return null; 1934 } 1935 } 1936 1937 /** 1938 * get the information of all network links 1939 * @hide 1940 */ 1941 public LinkQualityInfo[] getAllLinkQualityInfo() { 1942 try { 1943 LinkQualityInfo[] li = mService.getAllLinkQualityInfo(); 1944 return li; 1945 } catch (RemoteException e) { 1946 return null; 1947 } 1948 } 1949 1950 /** 1951 * Set sign in error notification to visible or in visible 1952 * 1953 * @param visible 1954 * @param networkType 1955 * 1956 * {@hide} 1957 */ 1958 public void setProvisioningNotificationVisible(boolean visible, int networkType, 1959 String extraInfo, String url) { 1960 try { 1961 mService.setProvisioningNotificationVisible(visible, networkType, extraInfo, url); 1962 } catch (RemoteException e) { 1963 } 1964 } 1965 1966 /** 1967 * Set the value for enabling/disabling airplane mode 1968 * 1969 * @param enable whether to enable airplane mode or not 1970 * 1971 * <p>This method requires the call to hold the permission 1972 * {@link android.Manifest.permission#CONNECTIVITY_INTERNAL}. 1973 * @hide 1974 */ 1975 public void setAirplaneMode(boolean enable) { 1976 try { 1977 mService.setAirplaneMode(enable); 1978 } catch (RemoteException e) { 1979 } 1980 } 1981 1982 /** {@hide} */ 1983 public void registerNetworkFactory(Messenger messenger, String name) { 1984 try { 1985 mService.registerNetworkFactory(messenger, name); 1986 } catch (RemoteException e) { } 1987 } 1988 1989 /** {@hide} */ 1990 public void unregisterNetworkFactory(Messenger messenger) { 1991 try { 1992 mService.unregisterNetworkFactory(messenger); 1993 } catch (RemoteException e) { } 1994 } 1995 1996 /** {@hide} */ 1997 public void registerNetworkAgent(Messenger messenger, NetworkInfo ni, LinkProperties lp, 1998 NetworkCapabilities nc, int score, NetworkMisc misc) { 1999 try { 2000 mService.registerNetworkAgent(messenger, ni, lp, nc, score, misc); 2001 } catch (RemoteException e) { } 2002 } 2003 2004 /** 2005 * Base class for NetworkRequest callbacks. Used for notifications about network 2006 * changes. Should be extended by applications wanting notifications. 2007 */ 2008 public static class NetworkCallback { 2009 /** @hide */ 2010 public static final int PRECHECK = 1; 2011 /** @hide */ 2012 public static final int AVAILABLE = 2; 2013 /** @hide */ 2014 public static final int LOSING = 3; 2015 /** @hide */ 2016 public static final int LOST = 4; 2017 /** @hide */ 2018 public static final int UNAVAIL = 5; 2019 /** @hide */ 2020 public static final int CAP_CHANGED = 6; 2021 /** @hide */ 2022 public static final int PROP_CHANGED = 7; 2023 /** @hide */ 2024 public static final int CANCELED = 8; 2025 2026 /** 2027 * @hide 2028 * Called whenever the framework connects to a network that it may use to 2029 * satisfy this request 2030 */ 2031 public void onPreCheck(Network network) {} 2032 2033 /** 2034 * Called when the framework connects and has declared new network ready for use. 2035 * This callback may be called more than once if the {@link Network} that is 2036 * satisfying the request changes. 2037 * 2038 * @param network The {@link Network} of the satisfying network. 2039 */ 2040 public void onAvailable(Network network) {} 2041 2042 /** 2043 * Called when the network is about to be disconnected. Often paired with an 2044 * {@link NetworkCallback#onAvailable} call with the new replacement network 2045 * for graceful handover. This may not be called if we have a hard loss 2046 * (loss without warning). This may be followed by either a 2047 * {@link NetworkCallback#onLost} call or a 2048 * {@link NetworkCallback#onAvailable} call for this network depending 2049 * on whether we lose or regain it. 2050 * 2051 * @param network The {@link Network} that is about to be disconnected. 2052 * @param maxMsToLive The time in ms the framework will attempt to keep the 2053 * network connected. Note that the network may suffer a 2054 * hard loss at any time. 2055 */ 2056 public void onLosing(Network network, int maxMsToLive) {} 2057 2058 /** 2059 * Called when the framework has a hard loss of the network or when the 2060 * graceful failure ends. 2061 * 2062 * @param network The {@link Network} lost. 2063 */ 2064 public void onLost(Network network) {} 2065 2066 /** 2067 * Called if no network is found in the given timeout time. If no timeout is given, 2068 * this will not be called. 2069 * @hide 2070 */ 2071 public void onUnavailable() {} 2072 2073 /** 2074 * Called when the network the framework connected to for this request 2075 * changes capabilities but still satisfies the stated need. 2076 * 2077 * @param network The {@link Network} whose capabilities have changed. 2078 * @param networkCapabilities The new {@link NetworkCapabilities} for this network. 2079 */ 2080 public void onCapabilitiesChanged(Network network, 2081 NetworkCapabilities networkCapabilities) {} 2082 2083 /** 2084 * Called when the network the framework connected to for this request 2085 * changes {@link LinkProperties}. 2086 * 2087 * @param network The {@link Network} whose link properties have changed. 2088 * @param linkProperties The new {@link LinkProperties} for this network. 2089 */ 2090 public void onLinkPropertiesChanged(Network network, LinkProperties linkProperties) {} 2091 2092 private NetworkRequest networkRequest; 2093 } 2094 2095 private static final int BASE = Protocol.BASE_CONNECTIVITY_MANAGER; 2096 /** @hide obj = pair(NetworkRequest, Network) */ 2097 public static final int CALLBACK_PRECHECK = BASE + 1; 2098 /** @hide obj = pair(NetworkRequest, Network) */ 2099 public static final int CALLBACK_AVAILABLE = BASE + 2; 2100 /** @hide obj = pair(NetworkRequest, Network), arg1 = ttl */ 2101 public static final int CALLBACK_LOSING = BASE + 3; 2102 /** @hide obj = pair(NetworkRequest, Network) */ 2103 public static final int CALLBACK_LOST = BASE + 4; 2104 /** @hide obj = NetworkRequest */ 2105 public static final int CALLBACK_UNAVAIL = BASE + 5; 2106 /** @hide obj = pair(NetworkRequest, Network) */ 2107 public static final int CALLBACK_CAP_CHANGED = BASE + 6; 2108 /** @hide obj = pair(NetworkRequest, Network) */ 2109 public static final int CALLBACK_IP_CHANGED = BASE + 7; 2110 /** @hide obj = NetworkRequest */ 2111 public static final int CALLBACK_RELEASED = BASE + 8; 2112 /** @hide */ 2113 public static final int CALLBACK_EXIT = BASE + 9; 2114 /** @hide obj = NetworkCapabilities, arg1 = seq number */ 2115 private static final int EXPIRE_LEGACY_REQUEST = BASE + 10; 2116 2117 private class CallbackHandler extends Handler { 2118 private final HashMap<NetworkRequest, NetworkCallback>mCallbackMap; 2119 private final AtomicInteger mRefCount; 2120 private static final String TAG = "ConnectivityManager.CallbackHandler"; 2121 private final ConnectivityManager mCm; 2122 2123 CallbackHandler(Looper looper, HashMap<NetworkRequest, NetworkCallback>callbackMap, 2124 AtomicInteger refCount, ConnectivityManager cm) { 2125 super(looper); 2126 mCallbackMap = callbackMap; 2127 mRefCount = refCount; 2128 mCm = cm; 2129 } 2130 2131 @Override 2132 public void handleMessage(Message message) { 2133 Log.d(TAG, "CM callback handler got msg " + message.what); 2134 switch (message.what) { 2135 case CALLBACK_PRECHECK: { 2136 NetworkRequest request = getNetworkRequest(message); 2137 NetworkCallback callbacks = getCallbacks(request); 2138 if (callbacks != null) { 2139 callbacks.onPreCheck(getNetwork(message)); 2140 } else { 2141 Log.e(TAG, "callback not found for PRECHECK message"); 2142 } 2143 break; 2144 } 2145 case CALLBACK_AVAILABLE: { 2146 NetworkRequest request = getNetworkRequest(message); 2147 NetworkCallback callbacks = getCallbacks(request); 2148 if (callbacks != null) { 2149 callbacks.onAvailable(getNetwork(message)); 2150 } else { 2151 Log.e(TAG, "callback not found for AVAILABLE message"); 2152 } 2153 break; 2154 } 2155 case CALLBACK_LOSING: { 2156 NetworkRequest request = getNetworkRequest(message); 2157 NetworkCallback callbacks = getCallbacks(request); 2158 if (callbacks != null) { 2159 callbacks.onLosing(getNetwork(message), message.arg1); 2160 } else { 2161 Log.e(TAG, "callback not found for LOSING message"); 2162 } 2163 break; 2164 } 2165 case CALLBACK_LOST: { 2166 NetworkRequest request = getNetworkRequest(message); 2167 NetworkCallback callbacks = getCallbacks(request); 2168 if (callbacks != null) { 2169 callbacks.onLost(getNetwork(message)); 2170 } else { 2171 Log.e(TAG, "callback not found for LOST message"); 2172 } 2173 break; 2174 } 2175 case CALLBACK_UNAVAIL: { 2176 NetworkRequest req = (NetworkRequest)message.obj; 2177 NetworkCallback callbacks = null; 2178 synchronized(mCallbackMap) { 2179 callbacks = mCallbackMap.get(req); 2180 } 2181 if (callbacks != null) { 2182 callbacks.onUnavailable(); 2183 } else { 2184 Log.e(TAG, "callback not found for UNAVAIL message"); 2185 } 2186 break; 2187 } 2188 case CALLBACK_CAP_CHANGED: { 2189 NetworkRequest request = getNetworkRequest(message); 2190 NetworkCallback callbacks = getCallbacks(request); 2191 if (callbacks != null) { 2192 Network network = getNetwork(message); 2193 NetworkCapabilities cap = mCm.getNetworkCapabilities(network); 2194 2195 callbacks.onCapabilitiesChanged(network, cap); 2196 } else { 2197 Log.e(TAG, "callback not found for CHANGED message"); 2198 } 2199 break; 2200 } 2201 case CALLBACK_IP_CHANGED: { 2202 NetworkRequest request = getNetworkRequest(message); 2203 NetworkCallback callbacks = getCallbacks(request); 2204 if (callbacks != null) { 2205 Network network = getNetwork(message); 2206 LinkProperties lp = mCm.getLinkProperties(network); 2207 2208 callbacks.onLinkPropertiesChanged(network, lp); 2209 } else { 2210 Log.e(TAG, "callback not found for CHANGED message"); 2211 } 2212 break; 2213 } 2214 case CALLBACK_RELEASED: { 2215 NetworkRequest req = (NetworkRequest)message.obj; 2216 NetworkCallback callbacks = null; 2217 synchronized(mCallbackMap) { 2218 callbacks = mCallbackMap.remove(req); 2219 } 2220 if (callbacks != null) { 2221 synchronized(mRefCount) { 2222 if (mRefCount.decrementAndGet() == 0) { 2223 getLooper().quit(); 2224 } 2225 } 2226 } else { 2227 Log.e(TAG, "callback not found for CANCELED message"); 2228 } 2229 break; 2230 } 2231 case CALLBACK_EXIT: { 2232 Log.d(TAG, "Listener quiting"); 2233 getLooper().quit(); 2234 break; 2235 } 2236 case EXPIRE_LEGACY_REQUEST: { 2237 expireRequest((NetworkCapabilities)message.obj, message.arg1); 2238 break; 2239 } 2240 } 2241 } 2242 2243 private NetworkRequest getNetworkRequest(Message msg) { 2244 return (NetworkRequest)(msg.obj); 2245 } 2246 private NetworkCallback getCallbacks(NetworkRequest req) { 2247 synchronized(mCallbackMap) { 2248 return mCallbackMap.get(req); 2249 } 2250 } 2251 private Network getNetwork(Message msg) { 2252 return new Network(msg.arg2); 2253 } 2254 private NetworkCallback removeCallbacks(Message msg) { 2255 NetworkRequest req = (NetworkRequest)msg.obj; 2256 synchronized(mCallbackMap) { 2257 return mCallbackMap.remove(req); 2258 } 2259 } 2260 } 2261 2262 private void incCallbackHandlerRefCount() { 2263 synchronized(sCallbackRefCount) { 2264 if (sCallbackRefCount.incrementAndGet() == 1) { 2265 // TODO - switch this over to a ManagerThread or expire it when done 2266 HandlerThread callbackThread = new HandlerThread("ConnectivityManager"); 2267 callbackThread.start(); 2268 sCallbackHandler = new CallbackHandler(callbackThread.getLooper(), 2269 sNetworkCallback, sCallbackRefCount, this); 2270 } 2271 } 2272 } 2273 2274 private void decCallbackHandlerRefCount() { 2275 synchronized(sCallbackRefCount) { 2276 if (sCallbackRefCount.decrementAndGet() == 0) { 2277 sCallbackHandler.obtainMessage(CALLBACK_EXIT).sendToTarget(); 2278 sCallbackHandler = null; 2279 } 2280 } 2281 } 2282 2283 static final HashMap<NetworkRequest, NetworkCallback> sNetworkCallback = 2284 new HashMap<NetworkRequest, NetworkCallback>(); 2285 static final AtomicInteger sCallbackRefCount = new AtomicInteger(0); 2286 static CallbackHandler sCallbackHandler = null; 2287 2288 private final static int LISTEN = 1; 2289 private final static int REQUEST = 2; 2290 2291 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, 2292 NetworkCallback networkCallback, int timeoutSec, int action, 2293 int legacyType) { 2294 if (networkCallback == null) { 2295 throw new IllegalArgumentException("null NetworkCallback"); 2296 } 2297 if (need == null) throw new IllegalArgumentException("null NetworkCapabilities"); 2298 try { 2299 incCallbackHandlerRefCount(); 2300 synchronized(sNetworkCallback) { 2301 if (action == LISTEN) { 2302 networkCallback.networkRequest = mService.listenForNetwork(need, 2303 new Messenger(sCallbackHandler), new Binder()); 2304 } else { 2305 networkCallback.networkRequest = mService.requestNetwork(need, 2306 new Messenger(sCallbackHandler), timeoutSec, new Binder(), legacyType); 2307 } 2308 if (networkCallback.networkRequest != null) { 2309 sNetworkCallback.put(networkCallback.networkRequest, networkCallback); 2310 } 2311 } 2312 } catch (RemoteException e) {} 2313 if (networkCallback.networkRequest == null) decCallbackHandlerRefCount(); 2314 return networkCallback.networkRequest; 2315 } 2316 2317 /** 2318 * Request a network to satisfy a set of {@link NetworkCapabilities}. 2319 * 2320 * This {@link NetworkRequest} will live until released via 2321 * {@link #unregisterNetworkCallback} or the calling application exits. 2322 * Status of the request can be followed by listening to the various 2323 * callbacks described in {@link NetworkCallback}. The {@link Network} 2324 * can be used to direct traffic to the network. 2325 * 2326 * @param request {@link NetworkRequest} describing this request. 2327 * @param networkCallback The {@link NetworkCallback} to be utilized for this 2328 * request. Note the callback must not be shared - they 2329 * uniquely specify this request. 2330 */ 2331 public void requestNetwork(NetworkRequest request, NetworkCallback networkCallback) { 2332 sendRequestForNetwork(request.networkCapabilities, networkCallback, 0, 2333 REQUEST, inferLegacyTypeForNetworkCapabilities(request.networkCapabilities)); 2334 } 2335 2336 /** 2337 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited 2338 * by a timeout. 2339 * 2340 * This function behaves identically to the non-timedout version, but if a suitable 2341 * network is not found within the given time (in milliseconds) the 2342 * {@link NetworkCallback#unavailable} callback is called. The request must 2343 * still be released normally by calling {@link releaseNetworkRequest}. 2344 * @param request {@link NetworkRequest} describing this request. 2345 * @param networkCallback The callbacks to be utilized for this request. Note 2346 * the callbacks must not be shared - they uniquely specify 2347 * this request. 2348 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network 2349 * before {@link NetworkCallback#unavailable} is called. 2350 * @hide 2351 */ 2352 public void requestNetwork(NetworkRequest request, NetworkCallback networkCallback, 2353 int timeoutMs) { 2354 sendRequestForNetwork(request.networkCapabilities, networkCallback, timeoutMs, 2355 REQUEST, inferLegacyTypeForNetworkCapabilities(request.networkCapabilities)); 2356 } 2357 2358 /** 2359 * The maximum number of milliseconds the framework will look for a suitable network 2360 * during a timeout-equiped call to {@link requestNetwork}. 2361 * {@hide} 2362 */ 2363 public final static int MAX_NETWORK_REQUEST_TIMEOUT_MS = 100 * 60 * 1000; 2364 2365 /** 2366 * The lookup key for a {@link Network} object included with the intent after 2367 * succesfully finding a network for the applications request. Retrieve it with 2368 * {@link android.content.Intent#getParcelableExtra(String)}. 2369 * @hide 2370 */ 2371 public static final String EXTRA_NETWORK_REQUEST_NETWORK = "networkRequestNetwork"; 2372 2373 /** 2374 * The lookup key for a {@link NetworkRequest} object included with the intent after 2375 * succesfully finding a network for the applications request. Retrieve it with 2376 * {@link android.content.Intent#getParcelableExtra(String)}. 2377 * @hide 2378 */ 2379 public static final String EXTRA_NETWORK_REQUEST_NETWORK_REQUEST = 2380 "networkRequestNetworkRequest"; 2381 2382 2383 /** 2384 * Request a network to satisfy a set of {@link NetworkCapabilities}. 2385 * 2386 * This function behavies identically to the version that takes a NetworkCallback, but instead 2387 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means 2388 * the request may outlive the calling application and get called back when a suitable 2389 * network is found. 2390 * <p> 2391 * The operation is an Intent broadcast that goes to a broadcast receiver that 2392 * you registered with {@link Context#registerReceiver} or through the 2393 * <receiver> tag in an AndroidManifest.xml file 2394 * <p> 2395 * The operation Intent is delivered with two extras, a {@link Network} typed 2396 * extra called {@link #EXTRA_NETWORK_REQUEST_NETWORK} and a {@link NetworkRequest} 2397 * typed extra called {@link #EXTRA_NETWORK_REQUEST_NETWORK_REQUEST} containing 2398 * the original requests parameters. It is important to create a new, 2399 * {@link NetworkCallback} based request before completing the processing of the 2400 * Intent to reserve the network or it will be released shortly after the Intent 2401 * is processed. 2402 * <p> 2403 * If there is already an request for this Intent registered (with the equality of 2404 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and 2405 * replaced by this one, effectively releasing the previous {@link NetworkRequest}. 2406 * <p> 2407 * The request may be released normally by calling {@link #unregisterNetworkCallback}. 2408 * 2409 * @param request {@link NetworkRequest} describing this request. 2410 * @param operation Action to perform when the network is available (corresponds 2411 * to the {@link NetworkCallback#onAvailable} call. Typically 2412 * comes from {@link PendingIntent#getBroadcast}. 2413 * @hide 2414 */ 2415 public void requestNetwork(NetworkRequest request, PendingIntent operation) { 2416 try { 2417 mService.pendingRequestForNetwork(request.networkCapabilities, operation); 2418 } catch (RemoteException e) {} 2419 } 2420 2421 /** 2422 * Registers to receive notifications about all networks which satisfy the given 2423 * {@link NetworkRequest}. The callbacks will continue to be called until 2424 * either the application exits or {@link #unregisterNetworkCallback} is called 2425 * 2426 * @param request {@link NetworkRequest} describing this request. 2427 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable 2428 * networks change state. 2429 */ 2430 public void registerNetworkCallback(NetworkRequest request, NetworkCallback networkCallback) { 2431 sendRequestForNetwork(request.networkCapabilities, networkCallback, 0, LISTEN, TYPE_NONE); 2432 } 2433 2434 /** 2435 * Unregisters callbacks about and possibly releases networks originating from 2436 * {@link #requestNetwork} and {@link #registerNetworkCallback} calls. If the 2437 * given {@code NetworkCallback} had previosuly been used with {@code #requestNetwork}, 2438 * any networks that had been connected to only to satisfy that request will be 2439 * disconnected. 2440 * 2441 * @param networkCallback The {@link NetworkCallback} used when making the request. 2442 */ 2443 public void unregisterNetworkCallback(NetworkCallback networkCallback) { 2444 if (networkCallback == null || networkCallback.networkRequest == null || 2445 networkCallback.networkRequest.requestId == REQUEST_ID_UNSET) { 2446 throw new IllegalArgumentException("Invalid NetworkCallback"); 2447 } 2448 try { 2449 mService.releaseNetworkRequest(networkCallback.networkRequest); 2450 } catch (RemoteException e) {} 2451 } 2452 2453 /** 2454 * Binds the current process to {@code network}. All Sockets created in the future 2455 * (and not explicitly bound via a bound SocketFactory from 2456 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to 2457 * {@code network}. All host name resolutions will be limited to {@code network} as well. 2458 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to 2459 * work and all host name resolutions will fail. This is by design so an application doesn't 2460 * accidentally use Sockets it thinks are still bound to a particular {@link Network}. 2461 * To clear binding pass {@code null} for {@code network}. Using individually bound 2462 * Sockets created by Network.getSocketFactory().createSocket() and 2463 * performing network-specific host name resolutions via 2464 * {@link Network#getAllByName Network.getAllByName} is preferred to calling 2465 * {@code setProcessDefaultNetwork}. 2466 * 2467 * @param network The {@link Network} to bind the current process to, or {@code null} to clear 2468 * the current binding. 2469 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid. 2470 */ 2471 public static boolean setProcessDefaultNetwork(Network network) { 2472 int netId = (network == null) ? NETID_UNSET : network.netId; 2473 if (netId == NetworkUtils.getNetworkBoundToProcess()) { 2474 return true; 2475 } 2476 if (NetworkUtils.bindProcessToNetwork(netId)) { 2477 // Must flush DNS cache as new network may have different DNS resolutions. 2478 InetAddress.clearDnsCache(); 2479 // Must flush socket pool as idle sockets will be bound to previous network and may 2480 // cause subsequent fetches to be performed on old network. 2481 NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged(); 2482 return true; 2483 } else { 2484 return false; 2485 } 2486 } 2487 2488 /** 2489 * Returns the {@link Network} currently bound to this process via 2490 * {@link #setProcessDefaultNetwork}, or {@code null} if no {@link Network} is explicitly bound. 2491 * 2492 * @return {@code Network} to which this process is bound, or {@code null}. 2493 */ 2494 public static Network getProcessDefaultNetwork() { 2495 int netId = NetworkUtils.getNetworkBoundToProcess(); 2496 if (netId == NETID_UNSET) return null; 2497 return new Network(netId); 2498 } 2499 2500 /** 2501 * Binds host resolutions performed by this process to {@code network}. 2502 * {@link #setProcessDefaultNetwork} takes precedence over this setting. 2503 * 2504 * @param network The {@link Network} to bind host resolutions from the current process to, or 2505 * {@code null} to clear the current binding. 2506 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid. 2507 * @hide 2508 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}. 2509 */ 2510 public static boolean setProcessDefaultNetworkForHostResolution(Network network) { 2511 return NetworkUtils.bindProcessToNetworkForHostResolution( 2512 network == null ? NETID_UNSET : network.netId); 2513 } 2514} 2515