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