ConnectivityManager.java revision 7a1c3fce478122b9f03464117dc94d44f7c1995e
1/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.net;
18
19import static com.android.internal.util.Preconditions.checkNotNull;
20
21import android.annotation.SdkConstant;
22import android.annotation.SdkConstant.SdkConstantType;
23import android.content.Context;
24import android.os.Binder;
25import android.os.Build.VERSION_CODES;
26import android.os.Messenger;
27import android.os.RemoteException;
28import android.provider.Settings;
29
30import java.net.InetAddress;
31
32/**
33 * Class that answers queries about the state of network connectivity. It also
34 * notifies applications when network connectivity changes. Get an instance
35 * of this class by calling
36 * {@link android.content.Context#getSystemService(String) Context.getSystemService(Context.CONNECTIVITY_SERVICE)}.
37 * <p>
38 * The primary responsibilities of this class are to:
39 * <ol>
40 * <li>Monitor network connections (Wi-Fi, GPRS, UMTS, etc.)</li>
41 * <li>Send broadcast intents when network connectivity changes</li>
42 * <li>Attempt to "fail over" to another network when connectivity to a network
43 * is lost</li>
44 * <li>Provide an API that allows applications to query the coarse-grained or fine-grained
45 * state of the available networks</li>
46 * </ol>
47 */
48public class ConnectivityManager {
49    private static final String TAG = "ConnectivityManager";
50
51    /**
52     * A change in network connectivity has occurred. A connection has either
53     * been established or lost. The NetworkInfo for the affected network is
54     * sent as an extra; it should be consulted to see what kind of
55     * connectivity event occurred.
56     * <p/>
57     * If this is a connection that was the result of failing over from a
58     * disconnected network, then the FAILOVER_CONNECTION boolean extra is
59     * set to true.
60     * <p/>
61     * For a loss of connectivity, if the connectivity manager is attempting
62     * to connect (or has already connected) to another network, the
63     * NetworkInfo for the new network is also passed as an extra. This lets
64     * any receivers of the broadcast know that they should not necessarily
65     * tell the user that no data traffic will be possible. Instead, the
66     * receiver should expect another broadcast soon, indicating either that
67     * the failover attempt succeeded (and so there is still overall data
68     * connectivity), or that the failover attempt failed, meaning that all
69     * connectivity has been lost.
70     * <p/>
71     * For a disconnect event, the boolean extra EXTRA_NO_CONNECTIVITY
72     * is set to {@code true} if there are no connected networks at all.
73     */
74    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
75    public static final String CONNECTIVITY_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
76
77    /**
78     * Identical to {@link #CONNECTIVITY_ACTION} broadcast, but sent without any
79     * applicable {@link Settings.Secure#CONNECTIVITY_CHANGE_DELAY}.
80     *
81     * @hide
82     */
83    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
84    public static final String CONNECTIVITY_ACTION_IMMEDIATE =
85            "android.net.conn.CONNECTIVITY_CHANGE_IMMEDIATE";
86
87    /**
88     * The lookup key for a {@link NetworkInfo} object. Retrieve with
89     * {@link android.content.Intent#getParcelableExtra(String)}.
90     *
91     * @deprecated Since {@link NetworkInfo} can vary based on UID, applications
92     *             should always obtain network information through
93     *             {@link #getActiveNetworkInfo()} or
94     *             {@link #getAllNetworkInfo()}.
95     * @see #EXTRA_NETWORK_TYPE
96     */
97    @Deprecated
98    public static final String EXTRA_NETWORK_INFO = "networkInfo";
99
100    /**
101     * Network type which triggered a {@link #CONNECTIVITY_ACTION} broadcast.
102     * Can be used with {@link #getNetworkInfo(int)} to get {@link NetworkInfo}
103     * state based on the calling application.
104     *
105     * @see android.content.Intent#getIntExtra(String, int)
106     */
107    public static final String EXTRA_NETWORK_TYPE = "networkType";
108
109    /**
110     * The lookup key for a boolean that indicates whether a connect event
111     * is for a network to which the connectivity manager was failing over
112     * following a disconnect on another network.
113     * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
114     */
115    public static final String EXTRA_IS_FAILOVER = "isFailover";
116    /**
117     * The lookup key for a {@link NetworkInfo} object. This is supplied when
118     * there is another network that it may be possible to connect to. Retrieve with
119     * {@link android.content.Intent#getParcelableExtra(String)}.
120     */
121    public static final String EXTRA_OTHER_NETWORK_INFO = "otherNetwork";
122    /**
123     * The lookup key for a boolean that indicates whether there is a
124     * complete lack of connectivity, i.e., no network is available.
125     * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
126     */
127    public static final String EXTRA_NO_CONNECTIVITY = "noConnectivity";
128    /**
129     * The lookup key for a string that indicates why an attempt to connect
130     * to a network failed. The string has no particular structure. It is
131     * intended to be used in notifications presented to users. Retrieve
132     * it with {@link android.content.Intent#getStringExtra(String)}.
133     */
134    public static final String EXTRA_REASON = "reason";
135    /**
136     * The lookup key for a string that provides optionally supplied
137     * extra information about the network state. The information
138     * may be passed up from the lower networking layers, and its
139     * meaning may be specific to a particular network type. Retrieve
140     * it with {@link android.content.Intent#getStringExtra(String)}.
141     */
142    public static final String EXTRA_EXTRA_INFO = "extraInfo";
143    /**
144     * The lookup key for an int that provides information about
145     * our connection to the internet at large.  0 indicates no connection,
146     * 100 indicates a great connection.  Retrieve it with
147     * {@link android.content.Intent#getIntExtra(String, int)}.
148     * {@hide}
149     */
150    public static final String EXTRA_INET_CONDITION = "inetCondition";
151
152    /**
153     * Broadcast action to indicate the change of data activity status
154     * (idle or active) on a network in a recent period.
155     * The network becomes active when data transmission is started, or
156     * idle if there is no data transmission for a period of time.
157     * {@hide}
158     */
159    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
160    public static final String ACTION_DATA_ACTIVITY_CHANGE = "android.net.conn.DATA_ACTIVITY_CHANGE";
161    /**
162     * The lookup key for an enum that indicates the network device type on which this data activity
163     * change happens.
164     * {@hide}
165     */
166    public static final String EXTRA_DEVICE_TYPE = "deviceType";
167    /**
168     * The lookup key for a boolean that indicates the device is active or not. {@code true} means
169     * it is actively sending or receiving data and {@code false} means it is idle.
170     * {@hide}
171     */
172    public static final String EXTRA_IS_ACTIVE = "isActive";
173
174    /**
175     * Broadcast Action: The setting for background data usage has changed
176     * values. Use {@link #getBackgroundDataSetting()} to get the current value.
177     * <p>
178     * If an application uses the network in the background, it should listen
179     * for this broadcast and stop using the background data if the value is
180     * {@code false}.
181     * <p>
182     *
183     * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability
184     *             of background data depends on several combined factors, and
185     *             this broadcast is no longer sent. Instead, when background
186     *             data is unavailable, {@link #getActiveNetworkInfo()} will now
187     *             appear disconnected. During first boot after a platform
188     *             upgrade, this broadcast will be sent once if
189     *             {@link #getBackgroundDataSetting()} was {@code false} before
190     *             the upgrade.
191     */
192    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
193    @Deprecated
194    public static final String ACTION_BACKGROUND_DATA_SETTING_CHANGED =
195            "android.net.conn.BACKGROUND_DATA_SETTING_CHANGED";
196
197    /**
198     * Broadcast Action: The network connection may not be good
199     * uses {@code ConnectivityManager.EXTRA_INET_CONDITION} and
200     * {@code ConnectivityManager.EXTRA_NETWORK_INFO} to specify
201     * the network and it's condition.
202     * @hide
203     */
204    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
205    public static final String INET_CONDITION_ACTION =
206            "android.net.conn.INET_CONDITION_ACTION";
207
208    /**
209     * Broadcast Action: A tetherable connection has come or gone.
210     * Uses {@code ConnectivityManager.EXTRA_AVAILABLE_TETHER},
211     * {@code ConnectivityManager.EXTRA_ACTIVE_TETHER} and
212     * {@code ConnectivityManager.EXTRA_ERRORED_TETHER} to indicate
213     * the current state of tethering.  Each include a list of
214     * interface names in that state (may be empty).
215     * @hide
216     */
217    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
218    public static final String ACTION_TETHER_STATE_CHANGED =
219            "android.net.conn.TETHER_STATE_CHANGED";
220
221    /**
222     * @hide
223     * gives a String[] listing all the interfaces configured for
224     * tethering and currently available for tethering.
225     */
226    public static final String EXTRA_AVAILABLE_TETHER = "availableArray";
227
228    /**
229     * @hide
230     * gives a String[] listing all the interfaces currently tethered
231     * (ie, has dhcp support and packets potentially forwarded/NATed)
232     */
233    public static final String EXTRA_ACTIVE_TETHER = "activeArray";
234
235    /**
236     * @hide
237     * gives a String[] listing all the interfaces we tried to tether and
238     * failed.  Use {@link #getLastTetherError} to find the error code
239     * for any interfaces listed here.
240     */
241    public static final String EXTRA_ERRORED_TETHER = "erroredArray";
242
243    /**
244     * Broadcast Action: The captive portal tracker has finished its test.
245     * Sent only while running Setup Wizard, in lieu of showing a user
246     * notification.
247     * @hide
248     */
249    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
250    public static final String ACTION_CAPTIVE_PORTAL_TEST_COMPLETED =
251            "android.net.conn.CAPTIVE_PORTAL_TEST_COMPLETED";
252    /**
253     * The lookup key for a boolean that indicates whether a captive portal was detected.
254     * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
255     * @hide
256     */
257    public static final String EXTRA_IS_CAPTIVE_PORTAL = "captivePortal";
258
259    /**
260     * The absence of a connection type.
261     * @hide
262     */
263    public static final int TYPE_NONE        = -1;
264
265    /**
266     * The Mobile data connection.  When active, all data traffic
267     * will use this network type's interface by default
268     * (it has a default route)
269     */
270    public static final int TYPE_MOBILE      = 0;
271    /**
272     * The WIFI data connection.  When active, all data traffic
273     * will use this network type's interface by default
274     * (it has a default route).
275     */
276    public static final int TYPE_WIFI        = 1;
277    /**
278     * An MMS-specific Mobile data connection.  This network type may use the
279     * same network interface as {@link #TYPE_MOBILE} or it may use a different
280     * one.  This is used by applications needing to talk to the carrier's
281     * Multimedia Messaging Service servers.
282     */
283    public static final int TYPE_MOBILE_MMS  = 2;
284    /**
285     * A SUPL-specific Mobile data connection.  This network type may use the
286     * same network interface as {@link #TYPE_MOBILE} or it may use a different
287     * one.  This is used by applications needing to talk to the carrier's
288     * Secure User Plane Location servers for help locating the device.
289     */
290    public static final int TYPE_MOBILE_SUPL = 3;
291    /**
292     * A DUN-specific Mobile data connection.  This network type may use the
293     * same network interface as {@link #TYPE_MOBILE} or it may use a different
294     * one.  This is sometimes by the system when setting up an upstream connection
295     * for tethering so that the carrier is aware of DUN traffic.
296     */
297    public static final int TYPE_MOBILE_DUN  = 4;
298    /**
299     * A High Priority Mobile data connection.  This network type uses the
300     * same network interface as {@link #TYPE_MOBILE} but the routing setup
301     * is different.  Only requesting processes will have access to the
302     * Mobile DNS servers and only IP's explicitly requested via {@link #requestRouteToHost}
303     * will route over this interface if no default route exists.
304     */
305    public static final int TYPE_MOBILE_HIPRI = 5;
306    /**
307     * The WiMAX data connection.  When active, all data traffic
308     * will use this network type's interface by default
309     * (it has a default route).
310     */
311    public static final int TYPE_WIMAX       = 6;
312
313    /**
314     * The Bluetooth data connection.  When active, all data traffic
315     * will use this network type's interface by default
316     * (it has a default route).
317     */
318    public static final int TYPE_BLUETOOTH   = 7;
319
320    /**
321     * Dummy data connection.  This should not be used on shipping devices.
322     */
323    public static final int TYPE_DUMMY       = 8;
324
325    /**
326     * The Ethernet data connection.  When active, all data traffic
327     * will use this network type's interface by default
328     * (it has a default route).
329     */
330    public static final int TYPE_ETHERNET    = 9;
331
332    /**
333     * Over the air Administration.
334     * {@hide}
335     */
336    public static final int TYPE_MOBILE_FOTA = 10;
337
338    /**
339     * IP Multimedia Subsystem.
340     * {@hide}
341     */
342    public static final int TYPE_MOBILE_IMS  = 11;
343
344    /**
345     * Carrier Branded Services.
346     * {@hide}
347     */
348    public static final int TYPE_MOBILE_CBS  = 12;
349
350    /**
351     * A Wi-Fi p2p connection. Only requesting processes will have access to
352     * the peers connected.
353     * {@hide}
354     */
355    public static final int TYPE_WIFI_P2P    = 13;
356
357    /** {@hide} */
358    public static final int MAX_RADIO_TYPE   = TYPE_WIFI_P2P;
359
360    /** {@hide} */
361    public static final int MAX_NETWORK_TYPE = TYPE_WIFI_P2P;
362
363    /**
364     * If you want to set the default network preference,you can directly
365     * change the networkAttributes array in framework's config.xml.
366     *
367     * @deprecated Since we support so many more networks now, the single
368     *             network default network preference can't really express
369     *             the hierarchy.  Instead, the default is defined by the
370     *             networkAttributes in config.xml.  You can determine
371     *             the current value by calling {@link #getNetworkPreference()}
372     *             from an App.
373     */
374    @Deprecated
375    public static final int DEFAULT_NETWORK_PREFERENCE = TYPE_WIFI;
376
377    /**
378     * Default value for {@link Settings.Global#CONNECTIVITY_CHANGE_DELAY} in
379     * milliseconds.  This was introduced because IPv6 routes seem to take a
380     * moment to settle - trying network activity before the routes are adjusted
381     * can lead to packets using the wrong interface or having the wrong IP address.
382     * This delay is a bit crude, but in the future hopefully we will have kernel
383     * notifications letting us know when it's safe to use the new network.
384     *
385     * @hide
386     */
387    public static final int CONNECTIVITY_CHANGE_DELAY_DEFAULT = 3000;
388
389    private final IConnectivityManager mService;
390
391    /**
392     * Tests if a given integer represents a valid network type.
393     * @param networkType the type to be tested
394     * @return a boolean.  {@code true} if the type is valid, else {@code false}
395     */
396    public static boolean isNetworkTypeValid(int networkType) {
397        return networkType >= 0 && networkType <= MAX_NETWORK_TYPE;
398    }
399
400    /**
401     * Returns a non-localized string representing a given network type.
402     * ONLY used for debugging output.
403     * @param type the type needing naming
404     * @return a String for the given type, or a string version of the type ("87")
405     * if no name is known.
406     * {@hide}
407     */
408    public static String getNetworkTypeName(int type) {
409        switch (type) {
410            case TYPE_MOBILE:
411                return "MOBILE";
412            case TYPE_WIFI:
413                return "WIFI";
414            case TYPE_MOBILE_MMS:
415                return "MOBILE_MMS";
416            case TYPE_MOBILE_SUPL:
417                return "MOBILE_SUPL";
418            case TYPE_MOBILE_DUN:
419                return "MOBILE_DUN";
420            case TYPE_MOBILE_HIPRI:
421                return "MOBILE_HIPRI";
422            case TYPE_WIMAX:
423                return "WIMAX";
424            case TYPE_BLUETOOTH:
425                return "BLUETOOTH";
426            case TYPE_DUMMY:
427                return "DUMMY";
428            case TYPE_ETHERNET:
429                return "ETHERNET";
430            case TYPE_MOBILE_FOTA:
431                return "MOBILE_FOTA";
432            case TYPE_MOBILE_IMS:
433                return "MOBILE_IMS";
434            case TYPE_MOBILE_CBS:
435                return "MOBILE_CBS";
436            case TYPE_WIFI_P2P:
437                return "WIFI_P2P";
438            default:
439                return Integer.toString(type);
440        }
441    }
442
443    /**
444     * Checks if a given type uses the cellular data connection.
445     * This should be replaced in the future by a network property.
446     * @param networkType the type to check
447     * @return a boolean - {@code true} if uses cellular network, else {@code false}
448     * {@hide}
449     */
450    public static boolean isNetworkTypeMobile(int networkType) {
451        switch (networkType) {
452            case TYPE_MOBILE:
453            case TYPE_MOBILE_MMS:
454            case TYPE_MOBILE_SUPL:
455            case TYPE_MOBILE_DUN:
456            case TYPE_MOBILE_HIPRI:
457            case TYPE_MOBILE_FOTA:
458            case TYPE_MOBILE_IMS:
459            case TYPE_MOBILE_CBS:
460                return true;
461            default:
462                return false;
463        }
464    }
465
466    /**
467     * Checks if the given network type is backed by a Wi-Fi radio.
468     *
469     * @hide
470     */
471    public static boolean isNetworkTypeWifi(int networkType) {
472        switch (networkType) {
473            case TYPE_WIFI:
474            case TYPE_WIFI_P2P:
475                return true;
476            default:
477                return false;
478        }
479    }
480
481    /**
482     * Specifies the preferred network type.  When the device has more
483     * than one type available the preferred network type will be used.
484     * Note that this made sense when we only had 2 network types,
485     * but with more and more default networks we need an array to list
486     * their ordering.  This will be deprecated soon.
487     *
488     * @param preference the network type to prefer over all others.  It is
489     *         unspecified what happens to the old preferred network in the
490     *         overall ordering.
491     */
492    public void setNetworkPreference(int preference) {
493        try {
494            mService.setNetworkPreference(preference);
495        } catch (RemoteException e) {
496        }
497    }
498
499    /**
500     * Retrieves the current preferred network type.
501     * Note that this made sense when we only had 2 network types,
502     * but with more and more default networks we need an array to list
503     * their ordering.  This will be deprecated soon.
504     *
505     * @return an integer representing the preferred network type
506     *
507     * <p>This method requires the caller to hold the permission
508     * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
509     */
510    public int getNetworkPreference() {
511        try {
512            return mService.getNetworkPreference();
513        } catch (RemoteException e) {
514            return -1;
515        }
516    }
517
518    /**
519     * Returns details about the currently active default data network. When
520     * connected, this network is the default route for outgoing connections.
521     * You should always check {@link NetworkInfo#isConnected()} before initiating
522     * network traffic. This may return {@code null} when there is no default
523     * network.
524     *
525     * @return a {@link NetworkInfo} object for the current default network
526     *        or {@code null} if no network default network is currently active
527     *
528     * <p>This method requires the call to hold the permission
529     * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
530     */
531    public NetworkInfo getActiveNetworkInfo() {
532        try {
533            return mService.getActiveNetworkInfo();
534        } catch (RemoteException e) {
535            return null;
536        }
537    }
538
539    /**
540     * Returns details about the currently active default data network
541     * for a given uid.  This is for internal use only to avoid spying
542     * other apps.
543     *
544     * @return a {@link NetworkInfo} object for the current default network
545     *        for the given uid or {@code null} if no default network is
546     *        available for the specified uid.
547     *
548     * <p>This method requires the caller to hold the permission
549     * {@link android.Manifest.permission#CONNECTIVITY_INTERNAL}
550     * {@hide}
551     */
552    public NetworkInfo getActiveNetworkInfoForUid(int uid) {
553        try {
554            return mService.getActiveNetworkInfoForUid(uid);
555        } catch (RemoteException e) {
556            return null;
557        }
558    }
559
560    /**
561     * Returns connection status information about a particular
562     * network type.
563     *
564     * @param networkType integer specifying which networkType in
565     *        which you're interested.
566     * @return a {@link NetworkInfo} object for the requested
567     *        network type or {@code null} if the type is not
568     *        supported by the device.
569     *
570     * <p>This method requires the call to hold the permission
571     * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
572     */
573    public NetworkInfo getNetworkInfo(int networkType) {
574        try {
575            return mService.getNetworkInfo(networkType);
576        } catch (RemoteException e) {
577            return null;
578        }
579    }
580
581    /**
582     * Returns connection status information about all network
583     * types supported by the device.
584     *
585     * @return an array of {@link NetworkInfo} objects.  Check each
586     * {@link NetworkInfo#getType} for which type each applies.
587     *
588     * <p>This method requires the call to hold the permission
589     * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
590     */
591    public NetworkInfo[] getAllNetworkInfo() {
592        try {
593            return mService.getAllNetworkInfo();
594        } catch (RemoteException e) {
595            return null;
596        }
597    }
598
599    /**
600     * Returns the IP information for the current default network.
601     *
602     * @return a {@link LinkProperties} object describing the IP info
603     *        for the current default network, or {@code null} if there
604     *        is no current default network.
605     *
606     * <p>This method requires the call to hold the permission
607     * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
608     * {@hide}
609     */
610    public LinkProperties getActiveLinkProperties() {
611        try {
612            return mService.getActiveLinkProperties();
613        } catch (RemoteException e) {
614            return null;
615        }
616    }
617
618    /**
619     * Returns the IP information for a given network type.
620     *
621     * @param networkType the network type of interest.
622     * @return a {@link LinkProperties} object describing the IP info
623     *        for the given networkType, or {@code null} if there is
624     *        no current default network.
625     *
626     * <p>This method requires the call to hold the permission
627     * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
628     * {@hide}
629     */
630    public LinkProperties getLinkProperties(int networkType) {
631        try {
632            return mService.getLinkProperties(networkType);
633        } catch (RemoteException e) {
634            return null;
635        }
636    }
637
638    /**
639     * Tells each network type to set its radio power state as directed.
640     *
641     * @param turnOn a boolean, {@code true} to turn the radios on,
642     *        {@code false} to turn them off.
643     * @return a boolean, {@code true} indicating success.  All network types
644     *        will be tried, even if some fail.
645     *
646     * <p>This method requires the call to hold the permission
647     * {@link android.Manifest.permission#CHANGE_NETWORK_STATE}.
648     * {@hide}
649     */
650    public boolean setRadios(boolean turnOn) {
651        try {
652            return mService.setRadios(turnOn);
653        } catch (RemoteException e) {
654            return false;
655        }
656    }
657
658    /**
659     * Tells a given networkType to set its radio power state as directed.
660     *
661     * @param networkType the int networkType of interest.
662     * @param turnOn a boolean, {@code true} to turn the radio on,
663     *        {@code} false to turn it off.
664     * @return a boolean, {@code true} indicating success.
665     *
666     * <p>This method requires the call to hold the permission
667     * {@link android.Manifest.permission#CHANGE_NETWORK_STATE}.
668     * {@hide}
669     */
670    public boolean setRadio(int networkType, boolean turnOn) {
671        try {
672            return mService.setRadio(networkType, turnOn);
673        } catch (RemoteException e) {
674            return false;
675        }
676    }
677
678    /**
679     * Tells the underlying networking system that the caller wants to
680     * begin using the named feature. The interpretation of {@code feature}
681     * is completely up to each networking implementation.
682     * <p>This method requires the caller to hold the permission
683     * {@link android.Manifest.permission#CHANGE_NETWORK_STATE}.
684     * @param networkType specifies which network the request pertains to
685     * @param feature the name of the feature to be used
686     * @return an integer value representing the outcome of the request.
687     * The interpretation of this value is specific to each networking
688     * implementation+feature combination, except that the value {@code -1}
689     * always indicates failure.
690     */
691    public int startUsingNetworkFeature(int networkType, String feature) {
692        try {
693            return mService.startUsingNetworkFeature(networkType, feature,
694                    new Binder());
695        } catch (RemoteException e) {
696            return -1;
697        }
698    }
699
700    /**
701     * Tells the underlying networking system that the caller is finished
702     * using the named feature. The interpretation of {@code feature}
703     * is completely up to each networking implementation.
704     * <p>This method requires the caller to hold the permission
705     * {@link android.Manifest.permission#CHANGE_NETWORK_STATE}.
706     * @param networkType specifies which network the request pertains to
707     * @param feature the name of the feature that is no longer needed
708     * @return an integer value representing the outcome of the request.
709     * The interpretation of this value is specific to each networking
710     * implementation+feature combination, except that the value {@code -1}
711     * always indicates failure.
712     */
713    public int stopUsingNetworkFeature(int networkType, String feature) {
714        try {
715            return mService.stopUsingNetworkFeature(networkType, feature);
716        } catch (RemoteException e) {
717            return -1;
718        }
719    }
720
721    /**
722     * Ensure that a network route exists to deliver traffic to the specified
723     * host via the specified network interface. An attempt to add a route that
724     * already exists is ignored, but treated as successful.
725     * <p>This method requires the caller to hold the permission
726     * {@link android.Manifest.permission#CHANGE_NETWORK_STATE}.
727     * @param networkType the type of the network over which traffic to the specified
728     * host is to be routed
729     * @param hostAddress the IP address of the host to which the route is desired
730     * @return {@code true} on success, {@code false} on failure
731     */
732    public boolean requestRouteToHost(int networkType, int hostAddress) {
733        InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
734
735        if (inetAddress == null) {
736            return false;
737        }
738
739        return requestRouteToHostAddress(networkType, inetAddress);
740    }
741
742    /**
743     * Ensure that a network route exists to deliver traffic to the specified
744     * host via the specified network interface. An attempt to add a route that
745     * already exists is ignored, but treated as successful.
746     * @param networkType the type of the network over which traffic to the specified
747     * host is to be routed
748     * @param hostAddress the IP address of the host to which the route is desired
749     * @return {@code true} on success, {@code false} on failure
750     * @hide
751     */
752    public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
753        byte[] address = hostAddress.getAddress();
754        try {
755            return mService.requestRouteToHostAddress(networkType, address);
756        } catch (RemoteException e) {
757            return false;
758        }
759    }
760
761    /**
762     * Returns the value of the setting for background data usage. If false,
763     * applications should not use the network if the application is not in the
764     * foreground. Developers should respect this setting, and check the value
765     * of this before performing any background data operations.
766     * <p>
767     * All applications that have background services that use the network
768     * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
769     * <p>
770     * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
771     * background data depends on several combined factors, and this method will
772     * always return {@code true}. Instead, when background data is unavailable,
773     * {@link #getActiveNetworkInfo()} will now appear disconnected.
774     *
775     * @return Whether background data usage is allowed.
776     */
777    @Deprecated
778    public boolean getBackgroundDataSetting() {
779        // assume that background data is allowed; final authority is
780        // NetworkInfo which may be blocked.
781        return true;
782    }
783
784    /**
785     * Sets the value of the setting for background data usage.
786     *
787     * @param allowBackgroundData Whether an application should use data while
788     *            it is in the background.
789     *
790     * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
791     * @see #getBackgroundDataSetting()
792     * @hide
793     */
794    @Deprecated
795    public void setBackgroundDataSetting(boolean allowBackgroundData) {
796        // ignored
797    }
798
799    /**
800     * Return quota status for the current active network, or {@code null} if no
801     * network is active. Quota status can change rapidly, so these values
802     * shouldn't be cached.
803     *
804     * <p>This method requires the call to hold the permission
805     * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
806     *
807     * @hide
808     */
809    public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
810        try {
811            return mService.getActiveNetworkQuotaInfo();
812        } catch (RemoteException e) {
813            return null;
814        }
815    }
816
817    /**
818     * Gets the value of the setting for enabling Mobile data.
819     *
820     * @return Whether mobile data is enabled.
821     *
822     * <p>This method requires the call to hold the permission
823     * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
824     * @hide
825     */
826    public boolean getMobileDataEnabled() {
827        try {
828            return mService.getMobileDataEnabled();
829        } catch (RemoteException e) {
830            return true;
831        }
832    }
833
834    /**
835     * Sets the persisted value for enabling/disabling Mobile data.
836     *
837     * @param enabled Whether the user wants the mobile data connection used
838     *            or not.
839     * @hide
840     */
841    public void setMobileDataEnabled(boolean enabled) {
842        try {
843            mService.setMobileDataEnabled(enabled);
844        } catch (RemoteException e) {
845        }
846    }
847
848    /**
849     * {@hide}
850     */
851    public ConnectivityManager(IConnectivityManager service) {
852        mService = checkNotNull(service, "missing IConnectivityManager");
853    }
854
855    /** {@hide} */
856    public static ConnectivityManager from(Context context) {
857        return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
858    }
859
860    /**
861     * Get the set of tetherable, available interfaces.  This list is limited by
862     * device configuration and current interface existence.
863     *
864     * @return an array of 0 or more Strings of tetherable interface names.
865     *
866     * <p>This method requires the call to hold the permission
867     * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
868     * {@hide}
869     */
870    public String[] getTetherableIfaces() {
871        try {
872            return mService.getTetherableIfaces();
873        } catch (RemoteException e) {
874            return new String[0];
875        }
876    }
877
878    /**
879     * Get the set of tethered interfaces.
880     *
881     * @return an array of 0 or more String of currently tethered interface names.
882     *
883     * <p>This method requires the call to hold the permission
884     * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
885     * {@hide}
886     */
887    public String[] getTetheredIfaces() {
888        try {
889            return mService.getTetheredIfaces();
890        } catch (RemoteException e) {
891            return new String[0];
892        }
893    }
894
895    /**
896     * Get the set of interface names which attempted to tether but
897     * failed.  Re-attempting to tether may cause them to reset to the Tethered
898     * state.  Alternatively, causing the interface to be destroyed and recreated
899     * may cause them to reset to the available state.
900     * {@link ConnectivityManager#getLastTetherError} can be used to get more
901     * information on the cause of the errors.
902     *
903     * @return an array of 0 or more String indicating the interface names
904     *        which failed to tether.
905     *
906     * <p>This method requires the call to hold the permission
907     * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
908     * {@hide}
909     */
910    public String[] getTetheringErroredIfaces() {
911        try {
912            return mService.getTetheringErroredIfaces();
913        } catch (RemoteException e) {
914            return new String[0];
915        }
916    }
917
918    /**
919     * Attempt to tether the named interface.  This will setup a dhcp server
920     * on the interface, forward and NAT IP packets and forward DNS requests
921     * to the best active upstream network interface.  Note that if no upstream
922     * IP network interface is available, dhcp will still run and traffic will be
923     * allowed between the tethered devices and this device, though upstream net
924     * access will of course fail until an upstream network interface becomes
925     * active.
926     *
927     * @param iface the interface name to tether.
928     * @return error a {@code TETHER_ERROR} value indicating success or failure type
929     *
930     * <p>This method requires the call to hold the permission
931     * {@link android.Manifest.permission#CHANGE_NETWORK_STATE}.
932     * {@hide}
933     */
934    public int tether(String iface) {
935        try {
936            return mService.tether(iface);
937        } catch (RemoteException e) {
938            return TETHER_ERROR_SERVICE_UNAVAIL;
939        }
940    }
941
942    /**
943     * Stop tethering the named interface.
944     *
945     * @param iface the interface name to untether.
946     * @return error a {@code TETHER_ERROR} value indicating success or failure type
947     *
948     * <p>This method requires the call to hold the permission
949     * {@link android.Manifest.permission#CHANGE_NETWORK_STATE}.
950     * {@hide}
951     */
952    public int untether(String iface) {
953        try {
954            return mService.untether(iface);
955        } catch (RemoteException e) {
956            return TETHER_ERROR_SERVICE_UNAVAIL;
957        }
958    }
959
960    /**
961     * Check if the device allows for tethering.  It may be disabled via
962     * {@code ro.tether.denied} system property, {@link Settings#TETHER_SUPPORTED} or
963     * due to device configuration.
964     *
965     * @return a boolean - {@code true} indicating Tethering is supported.
966     *
967     * <p>This method requires the call to hold the permission
968     * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
969     * {@hide}
970     */
971    public boolean isTetheringSupported() {
972        try {
973            return mService.isTetheringSupported();
974        } catch (RemoteException e) {
975            return false;
976        }
977    }
978
979    /**
980     * Get the list of regular expressions that define any tetherable
981     * USB network interfaces.  If USB tethering is not supported by the
982     * device, this list should be empty.
983     *
984     * @return an array of 0 or more regular expression Strings defining
985     *        what interfaces are considered tetherable usb interfaces.
986     *
987     * <p>This method requires the call to hold the permission
988     * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
989     * {@hide}
990     */
991    public String[] getTetherableUsbRegexs() {
992        try {
993            return mService.getTetherableUsbRegexs();
994        } catch (RemoteException e) {
995            return new String[0];
996        }
997    }
998
999    /**
1000     * Get the list of regular expressions that define any tetherable
1001     * Wifi network interfaces.  If Wifi tethering is not supported by the
1002     * device, this list should be empty.
1003     *
1004     * @return an array of 0 or more regular expression Strings defining
1005     *        what interfaces are considered tetherable wifi interfaces.
1006     *
1007     * <p>This method requires the call to hold the permission
1008     * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
1009     * {@hide}
1010     */
1011    public String[] getTetherableWifiRegexs() {
1012        try {
1013            return mService.getTetherableWifiRegexs();
1014        } catch (RemoteException e) {
1015            return new String[0];
1016        }
1017    }
1018
1019    /**
1020     * Get the list of regular expressions that define any tetherable
1021     * Bluetooth network interfaces.  If Bluetooth tethering is not supported by the
1022     * device, this list should be empty.
1023     *
1024     * @return an array of 0 or more regular expression Strings defining
1025     *        what interfaces are considered tetherable bluetooth interfaces.
1026     *
1027     * <p>This method requires the call to hold the permission
1028     * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
1029     * {@hide}
1030     */
1031    public String[] getTetherableBluetoothRegexs() {
1032        try {
1033            return mService.getTetherableBluetoothRegexs();
1034        } catch (RemoteException e) {
1035            return new String[0];
1036        }
1037    }
1038
1039    /**
1040     * Attempt to both alter the mode of USB and Tethering of USB.  A
1041     * utility method to deal with some of the complexity of USB - will
1042     * attempt to switch to Rndis and subsequently tether the resulting
1043     * interface on {@code true} or turn off tethering and switch off
1044     * Rndis on {@code false}.
1045     *
1046     * @param enable a boolean - {@code true} to enable tethering
1047     * @return error a {@code TETHER_ERROR} value indicating success or failure type
1048     *
1049     * <p>This method requires the call to hold the permission
1050     * {@link android.Manifest.permission#CHANGE_NETWORK_STATE}.
1051     * {@hide}
1052     */
1053    public int setUsbTethering(boolean enable) {
1054        try {
1055            return mService.setUsbTethering(enable);
1056        } catch (RemoteException e) {
1057            return TETHER_ERROR_SERVICE_UNAVAIL;
1058        }
1059    }
1060
1061    /** {@hide} */
1062    public static final int TETHER_ERROR_NO_ERROR           = 0;
1063    /** {@hide} */
1064    public static final int TETHER_ERROR_UNKNOWN_IFACE      = 1;
1065    /** {@hide} */
1066    public static final int TETHER_ERROR_SERVICE_UNAVAIL    = 2;
1067    /** {@hide} */
1068    public static final int TETHER_ERROR_UNSUPPORTED        = 3;
1069    /** {@hide} */
1070    public static final int TETHER_ERROR_UNAVAIL_IFACE      = 4;
1071    /** {@hide} */
1072    public static final int TETHER_ERROR_MASTER_ERROR       = 5;
1073    /** {@hide} */
1074    public static final int TETHER_ERROR_TETHER_IFACE_ERROR = 6;
1075    /** {@hide} */
1076    public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR = 7;
1077    /** {@hide} */
1078    public static final int TETHER_ERROR_ENABLE_NAT_ERROR     = 8;
1079    /** {@hide} */
1080    public static final int TETHER_ERROR_DISABLE_NAT_ERROR    = 9;
1081    /** {@hide} */
1082    public static final int TETHER_ERROR_IFACE_CFG_ERROR      = 10;
1083
1084    /**
1085     * Get a more detailed error code after a Tethering or Untethering
1086     * request asynchronously failed.
1087     *
1088     * @param iface The name of the interface of interest
1089     * @return error The error code of the last error tethering or untethering the named
1090     *               interface
1091     *
1092     * <p>This method requires the call to hold the permission
1093     * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
1094     * {@hide}
1095     */
1096    public int getLastTetherError(String iface) {
1097        try {
1098            return mService.getLastTetherError(iface);
1099        } catch (RemoteException e) {
1100            return TETHER_ERROR_SERVICE_UNAVAIL;
1101        }
1102    }
1103
1104    /**
1105     * Try to ensure the device stays awake until we connect with the next network.
1106     * Actually just holds a wakelock for a number of seconds while we try to connect
1107     * to any default networks.  This will expire if the timeout passes or if we connect
1108     * to a default after this is called.  For internal use only.
1109     *
1110     * @param forWhom the name of the network going down for logging purposes
1111     * @return {@code true} on success, {@code false} on failure
1112     *
1113     * <p>This method requires the call to hold the permission
1114     * {@link android.Manifest.permission#CONNECTIVITY_INTERNAL}.
1115     * {@hide}
1116     */
1117    public boolean requestNetworkTransitionWakelock(String forWhom) {
1118        try {
1119            mService.requestNetworkTransitionWakelock(forWhom);
1120            return true;
1121        } catch (RemoteException e) {
1122            return false;
1123        }
1124    }
1125
1126    /**
1127     * Report network connectivity status.  This is currently used only
1128     * to alter status bar UI.
1129     *
1130     * @param networkType The type of network you want to report on
1131     * @param percentage The quality of the connection 0 is bad, 100 is good
1132     *
1133     * <p>This method requires the call to hold the permission
1134     * {@link android.Manifest.permission#STATUS_BAR}.
1135     * {@hide}
1136     */
1137    public void reportInetCondition(int networkType, int percentage) {
1138        try {
1139            mService.reportInetCondition(networkType, percentage);
1140        } catch (RemoteException e) {
1141        }
1142    }
1143
1144    /**
1145     * Set a network-independent global http proxy.  This is not normally what you want
1146     * for typical HTTP proxies - they are general network dependent.  However if you're
1147     * doing something unusual like general internal filtering this may be useful.  On
1148     * a private network where the proxy is not accessible, you may break HTTP using this.
1149     *
1150     * @param proxyProperties The a {@link ProxyProperites} object defining the new global
1151     *        HTTP proxy.  A {@code null} value will clear the global HTTP proxy.
1152     *
1153     * <p>This method requires the call to hold the permission
1154     * {@link android.Manifest.permission#CONNECTIVITY_INTERNAL}.
1155     * {@hide}
1156     */
1157    public void setGlobalProxy(ProxyProperties p) {
1158        try {
1159            mService.setGlobalProxy(p);
1160        } catch (RemoteException e) {
1161        }
1162    }
1163
1164    /**
1165     * Retrieve any network-independent global HTTP proxy.
1166     *
1167     * @return {@link ProxyProperties} for the current global HTTP proxy or {@code null}
1168     *        if no global HTTP proxy is set.
1169     *
1170     * <p>This method requires the call to hold the permission
1171     * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
1172     * {@hide}
1173     */
1174    public ProxyProperties getGlobalProxy() {
1175        try {
1176            return mService.getGlobalProxy();
1177        } catch (RemoteException e) {
1178            return null;
1179        }
1180    }
1181
1182    /**
1183     * Get the HTTP proxy settings for the current default network.  Note that
1184     * if a global proxy is set, it will override any per-network setting.
1185     *
1186     * @return the {@link ProxyProperties} for the current HTTP proxy, or {@code null} if no
1187     *        HTTP proxy is active.
1188     *
1189     * <p>This method requires the call to hold the permission
1190     * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
1191     * {@hide}
1192     */
1193    public ProxyProperties getProxy() {
1194        try {
1195            return mService.getProxy();
1196        } catch (RemoteException e) {
1197            return null;
1198        }
1199    }
1200
1201    /**
1202     * Sets a secondary requirement bit for the given networkType.
1203     * This requirement bit is generally under the control of the carrier
1204     * or its agents and is not directly controlled by the user.
1205     *
1206     * @param networkType The network who's dependence has changed
1207     * @param met Boolean - true if network use is OK, false if not
1208     *
1209     * <p>This method requires the call to hold the permission
1210     * {@link android.Manifest.permission#CONNECTIVITY_INTERNAL}.
1211     * {@hide}
1212     */
1213    public void setDataDependency(int networkType, boolean met) {
1214        try {
1215            mService.setDataDependency(networkType, met);
1216        } catch (RemoteException e) {
1217        }
1218    }
1219
1220    /**
1221     * Returns true if the hardware supports the given network type
1222     * else it returns false.  This doesn't indicate we have coverage
1223     * or are authorized onto a network, just whether or not the
1224     * hardware supports it.  For example a GSM phone without a SIM
1225     * should still return {@code true} for mobile data, but a wifi only
1226     * tablet would return {@code false}.
1227     *
1228     * @param networkType The network type we'd like to check
1229     * @return {@code true} if supported, else {@code false}
1230     *
1231     * <p>This method requires the call to hold the permission
1232     * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
1233     * @hide
1234     */
1235    public boolean isNetworkSupported(int networkType) {
1236        try {
1237            return mService.isNetworkSupported(networkType);
1238        } catch (RemoteException e) {}
1239        return false;
1240    }
1241
1242    /**
1243     * Returns if the currently active data network is metered. A network is
1244     * classified as metered when the user is sensitive to heavy data usage on
1245     * that connection due to monetary costs, data limitations or
1246     * battery/performance issues. You should check this before doing large
1247     * data transfers, and warn the user or delay the operation until another
1248     * network is available.
1249     *
1250     * @return {@code true} if large transfers should be avoided, otherwise
1251     *        {@code false}.
1252     *
1253     * <p>This method requires the call to hold the permission
1254     * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
1255     */
1256    public boolean isActiveNetworkMetered() {
1257        try {
1258            return mService.isActiveNetworkMetered();
1259        } catch (RemoteException e) {
1260            return false;
1261        }
1262    }
1263
1264    /**
1265     * If the LockdownVpn mechanism is enabled, updates the vpn
1266     * with a reload of its profile.
1267     *
1268     * @return a boolean with {@code} indicating success
1269     *
1270     * <p>This method can only be called by the system UID
1271     * {@hide}
1272     */
1273    public boolean updateLockdownVpn() {
1274        try {
1275            return mService.updateLockdownVpn();
1276        } catch (RemoteException e) {
1277            return false;
1278        }
1279    }
1280
1281    /**
1282     * Signal that the captive portal check on the indicated network
1283     * is complete and we can turn the network on for general use.
1284     *
1285     * @param info the {@link NetworkInfo} object for the networkType
1286     *        in question.
1287     *
1288     * <p>This method requires the call to hold the permission
1289     * {@link android.Manifest.permission#CONNECTIVITY_INTERNAL}.
1290     * {@hide}
1291     */
1292    public void captivePortalCheckComplete(NetworkInfo info) {
1293        try {
1294            mService.captivePortalCheckComplete(info);
1295        } catch (RemoteException e) {
1296        }
1297    }
1298
1299    /**
1300     * Supply the backend messenger for a network tracker
1301     *
1302     * @param type NetworkType to set
1303     * @param messenger {@link Messenger}
1304     * {@hide}
1305     */
1306    public void supplyMessenger(int networkType, Messenger messenger) {
1307        try {
1308            mService.supplyMessenger(networkType, messenger);
1309        } catch (RemoteException e) {
1310        }
1311    }
1312}
1313