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