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