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