ConnectivityManager.java revision d2a458750e5a3d490af09cecb5c28370baf0a913
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 android.annotation.SdkConstant;
20import android.annotation.SdkConstant.SdkConstantType;
21import android.os.Binder;
22import android.os.RemoteException;
23
24import java.net.InetAddress;
25
26/**
27 * Class that answers queries about the state of network connectivity. It also
28 * notifies applications when network connectivity changes. Get an instance
29 * of this class by calling
30 * {@link android.content.Context#getSystemService(String) Context.getSystemService(Context.CONNECTIVITY_SERVICE)}.
31 * <p>
32 * The primary responsibilities of this class are to:
33 * <ol>
34 * <li>Monitor network connections (Wi-Fi, GPRS, UMTS, etc.)</li>
35 * <li>Send broadcast intents when network connectivity changes</li>
36 * <li>Attempt to "fail over" to another network when connectivity to a network
37 * is lost</li>
38 * <li>Provide an API that allows applications to query the coarse-grained or fine-grained
39 * state of the available networks</li>
40 * </ol>
41 */
42public class ConnectivityManager {
43    private static final String TAG = "ConnectivityManager";
44
45    /**
46     * A change in network connectivity has occurred. A connection has either
47     * been established or lost. The NetworkInfo for the affected network is
48     * sent as an extra; it should be consulted to see what kind of
49     * connectivity event occurred.
50     * <p/>
51     * If this is a connection that was the result of failing over from a
52     * disconnected network, then the FAILOVER_CONNECTION boolean extra is
53     * set to true.
54     * <p/>
55     * For a loss of connectivity, if the connectivity manager is attempting
56     * to connect (or has already connected) to another network, the
57     * NetworkInfo for the new network is also passed as an extra. This lets
58     * any receivers of the broadcast know that they should not necessarily
59     * tell the user that no data traffic will be possible. Instead, the
60     * reciever should expect another broadcast soon, indicating either that
61     * the failover attempt succeeded (and so there is still overall data
62     * connectivity), or that the failover attempt failed, meaning that all
63     * connectivity has been lost.
64     * <p/>
65     * For a disconnect event, the boolean extra EXTRA_NO_CONNECTIVITY
66     * is set to {@code true} if there are no connected networks at all.
67     */
68    public static final String CONNECTIVITY_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
69    /**
70     * The lookup key for a {@link NetworkInfo} object. Retrieve with
71     * {@link android.content.Intent#getParcelableExtra(String)}.
72     */
73    public static final String EXTRA_NETWORK_INFO = "networkInfo";
74    /**
75     * The lookup key for a boolean that indicates whether a connect event
76     * is for a network to which the connectivity manager was failing over
77     * following a disconnect on another network.
78     * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
79     */
80    public static final String EXTRA_IS_FAILOVER = "isFailover";
81    /**
82     * The lookup key for a {@link NetworkInfo} object. This is supplied when
83     * there is another network that it may be possible to connect to. Retrieve with
84     * {@link android.content.Intent#getParcelableExtra(String)}.
85     */
86    public static final String EXTRA_OTHER_NETWORK_INFO = "otherNetwork";
87    /**
88     * The lookup key for a boolean that indicates whether there is a
89     * complete lack of connectivity, i.e., no network is available.
90     * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
91     */
92    public static final String EXTRA_NO_CONNECTIVITY = "noConnectivity";
93    /**
94     * The lookup key for a string that indicates why an attempt to connect
95     * to a network failed. The string has no particular structure. It is
96     * intended to be used in notifications presented to users. Retrieve
97     * it with {@link android.content.Intent#getStringExtra(String)}.
98     */
99    public static final String EXTRA_REASON = "reason";
100    /**
101     * The lookup key for a string that provides optionally supplied
102     * extra information about the network state. The information
103     * may be passed up from the lower networking layers, and its
104     * meaning may be specific to a particular network type. Retrieve
105     * it with {@link android.content.Intent#getStringExtra(String)}.
106     */
107    public static final String EXTRA_EXTRA_INFO = "extraInfo";
108    /**
109     * The lookup key for an int that provides information about
110     * our connection to the internet at large.  0 indicates no connection,
111     * 100 indicates a great connection.  Retrieve it with
112     * {@link android.content.Intent#getIntExtra(String, int)}.
113     * {@hide}
114     */
115    public static final String EXTRA_INET_CONDITION = "inetCondition";
116
117    /**
118     * Broadcast Action: The setting for background data usage has changed
119     * values. Use {@link #getBackgroundDataSetting()} to get the current value.
120     * <p>
121     * If an application uses the network in the background, it should listen
122     * for this broadcast and stop using the background data if the value is
123     * {@code false}.
124     */
125    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
126    public static final String ACTION_BACKGROUND_DATA_SETTING_CHANGED =
127            "android.net.conn.BACKGROUND_DATA_SETTING_CHANGED";
128
129    /**
130     * Broadcast Action: The network connection may not be good
131     * uses {@code ConnectivityManager.EXTRA_INET_CONDITION} and
132     * {@code ConnectivityManager.EXTRA_NETWORK_INFO} to specify
133     * the network and it's condition.
134     * @hide
135     */
136    public static final String INET_CONDITION_ACTION =
137            "android.net.conn.INET_CONDITION_ACTION";
138
139    /**
140     * Broadcast Action: A tetherable connection has come or gone
141     * TODO - finish the doc
142     * @hide
143     */
144    public static final String ACTION_TETHER_STATE_CHANGED =
145            "android.net.conn.TETHER_STATE_CHANGED";
146
147    /**
148     * @hide
149     * gives a String[]
150     */
151    public static final String EXTRA_AVAILABLE_TETHER = "availableArray";
152
153    /**
154     * @hide
155     * gives a String[]
156     */
157    public static final String EXTRA_ACTIVE_TETHER = "activeArray";
158
159    /**
160     * @hide
161     * gives a String[]
162     */
163    public static final String EXTRA_ERRORED_TETHER = "erroredArray";
164
165    /**
166     * The Default Mobile data connection.  When active, all data traffic
167     * will use this connection by default.  Should not coexist with other
168     * default connections.
169     */
170    public static final int TYPE_MOBILE      = 0;
171    /**
172     * The Default WIFI data connection.  When active, all data traffic
173     * will use this connection by default.  Should not coexist with other
174     * default connections.
175     */
176    public static final int TYPE_WIFI        = 1;
177    /**
178     * An MMS-specific Mobile data connection.  This connection may be the
179     * same as {@link #TYPE_MOBILE} but it may be different.  This is used
180     * by applications needing to talk to the carrier's Multimedia Messaging
181     * Service servers.  It may coexist with default data connections.
182     */
183    public static final int TYPE_MOBILE_MMS  = 2;
184    /**
185     * A SUPL-specific Mobile data connection.  This connection may be the
186     * same as {@link #TYPE_MOBILE} but it may be different.  This is used
187     * by applications needing to talk to the carrier's Secure User Plane
188     * Location servers for help locating the device.  It may coexist with
189     * default data connections.
190     */
191    public static final int TYPE_MOBILE_SUPL = 3;
192    /**
193     * A DUN-specific Mobile data connection.  This connection may be the
194     * same as {@link #TYPE_MOBILE} but it may be different.  This is used
195     * by applicaitons performing a Dial Up Networking bridge so that
196     * the carrier is aware of DUN traffic.  It may coexist with default data
197     * connections.
198     */
199    public static final int TYPE_MOBILE_DUN  = 4;
200    /**
201     * A High Priority Mobile data connection.  This connection is typically
202     * the same as {@link #TYPE_MOBILE} but the routing setup is different.
203     * Only requesting processes will have access to the Mobile DNS servers
204     * and only IP's explicitly requested via {@link #requestRouteToHost}
205     * will route over this interface if a default route exists.
206     */
207    public static final int TYPE_MOBILE_HIPRI = 5;
208    /**
209     * The Default WiMAX data connection.  When active, all data traffic
210     * will use this connection by default.  Should not coexist with other
211     * default connections.
212     */
213    public static final int TYPE_WIMAX       = 6;
214
215    /**
216     * Bluetooth data connection. This is used for Bluetooth reverse tethering.
217     */
218    public static final int TYPE_BLUETOOTH   = 7;
219
220    /**
221     * Dummy data connection.  This should not be used on shipping devices.
222     */
223    public static final int TYPE_DUMMY       = 8;
224
225    /**
226     * Ethernet data connection.  This may be via USB dongle or more
227     * traditional means.
228     */
229    public static final int TYPE_ETHERNET    = 9;
230
231    /**
232     * Over the air Adminstration.
233     * {@hide}
234     */
235    public static final int TYPE_MOBILE_FOTA = 10;
236
237    /**
238     * IP Multimedia Subsystem
239     * {@hide}
240     */
241    public static final int TYPE_MOBILE_IMS  = 11;
242
243    /**
244     * Carrier Branded Services
245     * {@hide}
246     */
247    public static final int TYPE_MOBILE_CBS  = 12;
248
249    /** {@hide} */
250    public static final int MAX_RADIO_TYPE   = TYPE_MOBILE_CBS;
251
252    /** {@hide} */
253    public static final int MAX_NETWORK_TYPE = TYPE_MOBILE_CBS;
254
255    public static final int DEFAULT_NETWORK_PREFERENCE = TYPE_WIFI;
256
257    private final IConnectivityManager mService;
258
259    public static boolean isNetworkTypeValid(int networkType) {
260        return networkType >= 0 && networkType <= MAX_NETWORK_TYPE;
261    }
262
263    /** {@hide} */
264    public static String getNetworkTypeName(int type) {
265        switch (type) {
266            case TYPE_MOBILE:
267                return "MOBILE";
268            case TYPE_WIFI:
269                return "WIFI";
270            case TYPE_MOBILE_MMS:
271                return "MOBILE_MMS";
272            case TYPE_MOBILE_SUPL:
273                return "MOBILE_SUPL";
274            case TYPE_MOBILE_DUN:
275                return "MOBILE_DUN";
276            case TYPE_MOBILE_HIPRI:
277                return "MOBILE_HIPRI";
278            case TYPE_WIMAX:
279                return "WIMAX";
280            case TYPE_BLUETOOTH:
281                return "BLUETOOTH";
282            case TYPE_DUMMY:
283                return "DUMMY";
284            case TYPE_ETHERNET:
285                return "ETHERNET";
286            case TYPE_MOBILE_FOTA:
287                return "MOBILE_FOTA";
288            case TYPE_MOBILE_IMS:
289                return "MOBILE_IMS";
290            case TYPE_MOBILE_CBS:
291                return "MOBILE_CBS";
292            default:
293                return Integer.toString(type);
294        }
295    }
296
297    /** {@hide} */
298    public static boolean isNetworkTypeMobile(int networkType) {
299        switch (networkType) {
300            case TYPE_MOBILE:
301            case TYPE_MOBILE_MMS:
302            case TYPE_MOBILE_SUPL:
303            case TYPE_MOBILE_DUN:
304            case TYPE_MOBILE_HIPRI:
305            case TYPE_MOBILE_FOTA:
306            case TYPE_MOBILE_IMS:
307            case TYPE_MOBILE_CBS:
308                return true;
309            default:
310                return false;
311        }
312    }
313
314    public void setNetworkPreference(int preference) {
315        try {
316            mService.setNetworkPreference(preference);
317        } catch (RemoteException e) {
318        }
319    }
320
321    public int getNetworkPreference() {
322        try {
323            return mService.getNetworkPreference();
324        } catch (RemoteException e) {
325            return -1;
326        }
327    }
328
329    public NetworkInfo getActiveNetworkInfo() {
330        try {
331            return mService.getActiveNetworkInfo();
332        } catch (RemoteException e) {
333            return null;
334        }
335    }
336
337    /** {@hide} */
338    public NetworkInfo getActiveNetworkInfoForUid(int uid) {
339        try {
340            return mService.getActiveNetworkInfoForUid(uid);
341        } catch (RemoteException e) {
342            return null;
343        }
344    }
345
346    public NetworkInfo getNetworkInfo(int networkType) {
347        try {
348            return mService.getNetworkInfo(networkType);
349        } catch (RemoteException e) {
350            return null;
351        }
352    }
353
354    public NetworkInfo[] getAllNetworkInfo() {
355        try {
356            return mService.getAllNetworkInfo();
357        } catch (RemoteException e) {
358            return null;
359        }
360    }
361
362    /** {@hide} */
363    public LinkProperties getActiveLinkProperties() {
364        try {
365            return mService.getActiveLinkProperties();
366        } catch (RemoteException e) {
367            return null;
368        }
369    }
370
371    /** {@hide} */
372    public LinkProperties getLinkProperties(int networkType) {
373        try {
374            return mService.getLinkProperties(networkType);
375        } catch (RemoteException e) {
376            return null;
377        }
378    }
379
380    /** {@hide} */
381    public boolean setRadios(boolean turnOn) {
382        try {
383            return mService.setRadios(turnOn);
384        } catch (RemoteException e) {
385            return false;
386        }
387    }
388
389    /** {@hide} */
390    public boolean setRadio(int networkType, boolean turnOn) {
391        try {
392            return mService.setRadio(networkType, turnOn);
393        } catch (RemoteException e) {
394            return false;
395        }
396    }
397
398    /**
399     * Tells the underlying networking system that the caller wants to
400     * begin using the named feature. The interpretation of {@code feature}
401     * is completely up to each networking implementation.
402     * @param networkType specifies which network the request pertains to
403     * @param feature the name of the feature to be used
404     * @return an integer value representing the outcome of the request.
405     * The interpretation of this value is specific to each networking
406     * implementation+feature combination, except that the value {@code -1}
407     * always indicates failure.
408     */
409    public int startUsingNetworkFeature(int networkType, String feature) {
410        try {
411            return mService.startUsingNetworkFeature(networkType, feature,
412                    new Binder());
413        } catch (RemoteException e) {
414            return -1;
415        }
416    }
417
418    /**
419     * Tells the underlying networking system that the caller is finished
420     * using the named feature. The interpretation of {@code feature}
421     * is completely up to each networking implementation.
422     * @param networkType specifies which network the request pertains to
423     * @param feature the name of the feature that is no longer needed
424     * @return an integer value representing the outcome of the request.
425     * The interpretation of this value is specific to each networking
426     * implementation+feature combination, except that the value {@code -1}
427     * always indicates failure.
428     */
429    public int stopUsingNetworkFeature(int networkType, String feature) {
430        try {
431            return mService.stopUsingNetworkFeature(networkType, feature);
432        } catch (RemoteException e) {
433            return -1;
434        }
435    }
436
437    /**
438     * Ensure that a network route exists to deliver traffic to the specified
439     * host via the specified network interface. An attempt to add a route that
440     * already exists is ignored, but treated as successful.
441     * @param networkType the type of the network over which traffic to the specified
442     * host is to be routed
443     * @param hostAddress the IP address of the host to which the route is desired
444     * @return {@code true} on success, {@code false} on failure
445     */
446    public boolean requestRouteToHost(int networkType, int hostAddress) {
447        InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
448
449        if (inetAddress == null) {
450            return false;
451        }
452
453        return requestRouteToHostAddress(networkType, inetAddress);
454    }
455
456    /**
457     * Ensure that a network route exists to deliver traffic to the specified
458     * host via the specified network interface. An attempt to add a route that
459     * already exists is ignored, but treated as successful.
460     * @param networkType the type of the network over which traffic to the specified
461     * host is to be routed
462     * @param hostAddress the IP address of the host to which the route is desired
463     * @return {@code true} on success, {@code false} on failure
464     * @hide
465     */
466    public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
467        byte[] address = hostAddress.getAddress();
468        try {
469            return mService.requestRouteToHostAddress(networkType, address);
470        } catch (RemoteException e) {
471            return false;
472        }
473    }
474
475    /**
476     * Returns the value of the setting for background data usage. If false,
477     * applications should not use the network if the application is not in the
478     * foreground. Developers should respect this setting, and check the value
479     * of this before performing any background data operations.
480     * <p>
481     * All applications that have background services that use the network
482     * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
483     *
484     * @return Whether background data usage is allowed.
485     */
486    public boolean getBackgroundDataSetting() {
487        try {
488            return mService.getBackgroundDataSetting();
489        } catch (RemoteException e) {
490            // Err on the side of safety
491            return false;
492        }
493    }
494
495    /**
496     * Sets the value of the setting for background data usage.
497     *
498     * @param allowBackgroundData Whether an application should use data while
499     *            it is in the background.
500     *
501     * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
502     * @see #getBackgroundDataSetting()
503     * @hide
504     */
505    public void setBackgroundDataSetting(boolean allowBackgroundData) {
506        try {
507            mService.setBackgroundDataSetting(allowBackgroundData);
508        } catch (RemoteException e) {
509        }
510    }
511
512    /**
513     * Gets the value of the setting for enabling Mobile data.
514     *
515     * @return Whether mobile data is enabled.
516     * @hide
517     */
518    public boolean getMobileDataEnabled() {
519        try {
520            return mService.getMobileDataEnabled();
521        } catch (RemoteException e) {
522            return true;
523        }
524    }
525
526    /**
527     * Sets the persisted value for enabling/disabling Mobile data.
528     *
529     * @param enabled Whether the mobile data connection should be
530     *            used or not.
531     * @hide
532     */
533    public void setMobileDataEnabled(boolean enabled) {
534        try {
535            mService.setMobileDataEnabled(enabled);
536        } catch (RemoteException e) {
537        }
538    }
539
540    /**
541     * {@hide}
542     */
543    public ConnectivityManager(IConnectivityManager service) {
544        if (service == null) {
545            throw new IllegalArgumentException("missing IConnectivityManager");
546        }
547        mService = service;
548    }
549
550    /**
551     * {@hide}
552     */
553    public String[] getTetherableIfaces() {
554        try {
555            return mService.getTetherableIfaces();
556        } catch (RemoteException e) {
557            return new String[0];
558        }
559    }
560
561    /**
562     * {@hide}
563     */
564    public String[] getTetheredIfaces() {
565        try {
566            return mService.getTetheredIfaces();
567        } catch (RemoteException e) {
568            return new String[0];
569        }
570    }
571
572    /**
573     * {@hide}
574     */
575    public String[] getTetheringErroredIfaces() {
576        try {
577            return mService.getTetheringErroredIfaces();
578        } catch (RemoteException e) {
579            return new String[0];
580        }
581    }
582
583    /**
584     * @return error A TETHER_ERROR value indicating success or failure type
585     * {@hide}
586     */
587    public int tether(String iface) {
588        try {
589            return mService.tether(iface);
590        } catch (RemoteException e) {
591            return TETHER_ERROR_SERVICE_UNAVAIL;
592        }
593    }
594
595    /**
596     * @return error A TETHER_ERROR value indicating success or failure type
597     * {@hide}
598     */
599    public int untether(String iface) {
600        try {
601            return mService.untether(iface);
602        } catch (RemoteException e) {
603            return TETHER_ERROR_SERVICE_UNAVAIL;
604        }
605    }
606
607    /**
608     * {@hide}
609     */
610    public boolean isTetheringSupported() {
611        try {
612            return mService.isTetheringSupported();
613        } catch (RemoteException e) {
614            return false;
615        }
616    }
617
618    /**
619     * {@hide}
620     */
621    public String[] getTetherableUsbRegexs() {
622        try {
623            return mService.getTetherableUsbRegexs();
624        } catch (RemoteException e) {
625            return new String[0];
626        }
627    }
628
629    /**
630     * {@hide}
631     */
632    public String[] getTetherableWifiRegexs() {
633        try {
634            return mService.getTetherableWifiRegexs();
635        } catch (RemoteException e) {
636            return new String[0];
637        }
638    }
639
640    /**
641     * {@hide}
642     */
643    public String[] getTetherableBluetoothRegexs() {
644        try {
645            return mService.getTetherableBluetoothRegexs();
646        } catch (RemoteException e) {
647            return new String[0];
648        }
649    }
650
651    /** {@hide} */
652    public static final int TETHER_ERROR_NO_ERROR           = 0;
653    /** {@hide} */
654    public static final int TETHER_ERROR_UNKNOWN_IFACE      = 1;
655    /** {@hide} */
656    public static final int TETHER_ERROR_SERVICE_UNAVAIL    = 2;
657    /** {@hide} */
658    public static final int TETHER_ERROR_UNSUPPORTED        = 3;
659    /** {@hide} */
660    public static final int TETHER_ERROR_UNAVAIL_IFACE      = 4;
661    /** {@hide} */
662    public static final int TETHER_ERROR_MASTER_ERROR       = 5;
663    /** {@hide} */
664    public static final int TETHER_ERROR_TETHER_IFACE_ERROR = 6;
665    /** {@hide} */
666    public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR = 7;
667    /** {@hide} */
668    public static final int TETHER_ERROR_ENABLE_NAT_ERROR     = 8;
669    /** {@hide} */
670    public static final int TETHER_ERROR_DISABLE_NAT_ERROR    = 9;
671    /** {@hide} */
672    public static final int TETHER_ERROR_IFACE_CFG_ERROR      = 10;
673
674    /**
675     * @param iface The name of the interface we're interested in
676     * @return error The error code of the last error tethering or untethering the named
677     *               interface
678     * {@hide}
679     */
680    public int getLastTetherError(String iface) {
681        try {
682            return mService.getLastTetherError(iface);
683        } catch (RemoteException e) {
684            return TETHER_ERROR_SERVICE_UNAVAIL;
685        }
686    }
687
688    /**
689     * Ensure the device stays awake until we connect with the next network
690     * @param forWhome The name of the network going down for logging purposes
691     * @return {@code true} on success, {@code false} on failure
692     * {@hide}
693     */
694    public boolean requestNetworkTransitionWakelock(String forWhom) {
695        try {
696            mService.requestNetworkTransitionWakelock(forWhom);
697            return true;
698        } catch (RemoteException e) {
699            return false;
700        }
701    }
702
703    /**
704     * @param networkType The type of network you want to report on
705     * @param percentage The quality of the connection 0 is bad, 100 is good
706     * {@hide}
707     */
708    public void reportInetCondition(int networkType, int percentage) {
709        try {
710            mService.reportInetCondition(networkType, percentage);
711        } catch (RemoteException e) {
712        }
713    }
714
715    /**
716     * @param proxyProperties The definition for the new global http proxy
717     * {@hide}
718     */
719    public void setGlobalProxy(ProxyProperties p) {
720        try {
721            mService.setGlobalProxy(p);
722        } catch (RemoteException e) {
723        }
724    }
725
726    /**
727     * @return proxyProperties for the current global proxy
728     * {@hide}
729     */
730    public ProxyProperties getGlobalProxy() {
731        try {
732            return mService.getGlobalProxy();
733        } catch (RemoteException e) {
734            return null;
735        }
736    }
737
738    /**
739     * @return proxyProperties for the current proxy (global if set, network specific if not)
740     * {@hide}
741     */
742    public ProxyProperties getProxy() {
743        try {
744            return mService.getProxy();
745        } catch (RemoteException e) {
746            return null;
747        }
748    }
749
750    /**
751     * @param networkType The network who's dependence has changed
752     * @param met Boolean - true if network use is ok, false if not
753     * {@hide}
754     */
755    public void setDataDependency(int networkType, boolean met) {
756        try {
757            mService.setDataDependency(networkType, met);
758        } catch (RemoteException e) {
759        }
760    }
761}
762