ConnectivityManager.java revision c006f1aec15454782c35e028ad64d79a5c161cc1
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    static public boolean isNetworkTypeValid(int networkType) {
260        return networkType >= 0 && networkType <= MAX_NETWORK_TYPE;
261    }
262
263    public void setNetworkPreference(int preference) {
264        try {
265            mService.setNetworkPreference(preference);
266        } catch (RemoteException e) {
267        }
268    }
269
270    public int getNetworkPreference() {
271        try {
272            return mService.getNetworkPreference();
273        } catch (RemoteException e) {
274            return -1;
275        }
276    }
277
278    public NetworkInfo getActiveNetworkInfo() {
279        try {
280            return mService.getActiveNetworkInfo();
281        } catch (RemoteException e) {
282            return null;
283        }
284    }
285
286    /** {@hide} */
287    public NetworkInfo getActiveNetworkInfoForUid(int uid) {
288        try {
289            return mService.getActiveNetworkInfoForUid(uid);
290        } catch (RemoteException e) {
291            return null;
292        }
293    }
294
295    public NetworkInfo getNetworkInfo(int networkType) {
296        try {
297            return mService.getNetworkInfo(networkType);
298        } catch (RemoteException e) {
299            return null;
300        }
301    }
302
303    public NetworkInfo[] getAllNetworkInfo() {
304        try {
305            return mService.getAllNetworkInfo();
306        } catch (RemoteException e) {
307            return null;
308        }
309    }
310
311    /** {@hide} */
312    public LinkProperties getActiveLinkProperties() {
313        try {
314            return mService.getActiveLinkProperties();
315        } catch (RemoteException e) {
316            return null;
317        }
318    }
319
320    /** {@hide} */
321    public LinkProperties getLinkProperties(int networkType) {
322        try {
323            return mService.getLinkProperties(networkType);
324        } catch (RemoteException e) {
325            return null;
326        }
327    }
328
329    /** {@hide} */
330    public boolean setRadios(boolean turnOn) {
331        try {
332            return mService.setRadios(turnOn);
333        } catch (RemoteException e) {
334            return false;
335        }
336    }
337
338    /** {@hide} */
339    public boolean setRadio(int networkType, boolean turnOn) {
340        try {
341            return mService.setRadio(networkType, turnOn);
342        } catch (RemoteException e) {
343            return false;
344        }
345    }
346
347    /**
348     * Tells the underlying networking system that the caller wants to
349     * begin using the named feature. The interpretation of {@code feature}
350     * is completely up to each networking implementation.
351     * @param networkType specifies which network the request pertains to
352     * @param feature the name of the feature to be used
353     * @return an integer value representing the outcome of the request.
354     * The interpretation of this value is specific to each networking
355     * implementation+feature combination, except that the value {@code -1}
356     * always indicates failure.
357     */
358    public int startUsingNetworkFeature(int networkType, String feature) {
359        try {
360            return mService.startUsingNetworkFeature(networkType, feature,
361                    new Binder());
362        } catch (RemoteException e) {
363            return -1;
364        }
365    }
366
367    /**
368     * Tells the underlying networking system that the caller is finished
369     * using the named feature. The interpretation of {@code feature}
370     * is completely up to each networking implementation.
371     * @param networkType specifies which network the request pertains to
372     * @param feature the name of the feature that is no longer needed
373     * @return an integer value representing the outcome of the request.
374     * The interpretation of this value is specific to each networking
375     * implementation+feature combination, except that the value {@code -1}
376     * always indicates failure.
377     */
378    public int stopUsingNetworkFeature(int networkType, String feature) {
379        try {
380            return mService.stopUsingNetworkFeature(networkType, feature);
381        } catch (RemoteException e) {
382            return -1;
383        }
384    }
385
386    /**
387     * Ensure that a network route exists to deliver traffic to the specified
388     * host via the specified network interface. An attempt to add a route that
389     * already exists is ignored, but treated as successful.
390     * @param networkType the type of the network over which traffic to the specified
391     * host is to be routed
392     * @param hostAddress the IP address of the host to which the route is desired
393     * @return {@code true} on success, {@code false} on failure
394     */
395    public boolean requestRouteToHost(int networkType, int hostAddress) {
396        InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
397
398        if (inetAddress == null) {
399            return false;
400        }
401
402        return requestRouteToHostAddress(networkType, inetAddress);
403    }
404
405    /**
406     * Ensure that a network route exists to deliver traffic to the specified
407     * host via the specified network interface. An attempt to add a route that
408     * already exists is ignored, but treated as successful.
409     * @param networkType the type of the network over which traffic to the specified
410     * host is to be routed
411     * @param hostAddress the IP address of the host to which the route is desired
412     * @return {@code true} on success, {@code false} on failure
413     * @hide
414     */
415    public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
416        byte[] address = hostAddress.getAddress();
417        try {
418            return mService.requestRouteToHostAddress(networkType, address);
419        } catch (RemoteException e) {
420            return false;
421        }
422    }
423
424    /**
425     * Returns the value of the setting for background data usage. If false,
426     * applications should not use the network if the application is not in the
427     * foreground. Developers should respect this setting, and check the value
428     * of this before performing any background data operations.
429     * <p>
430     * All applications that have background services that use the network
431     * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
432     *
433     * @return Whether background data usage is allowed.
434     */
435    public boolean getBackgroundDataSetting() {
436        try {
437            return mService.getBackgroundDataSetting();
438        } catch (RemoteException e) {
439            // Err on the side of safety
440            return false;
441        }
442    }
443
444    /**
445     * Sets the value of the setting for background data usage.
446     *
447     * @param allowBackgroundData Whether an application should use data while
448     *            it is in the background.
449     *
450     * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
451     * @see #getBackgroundDataSetting()
452     * @hide
453     */
454    public void setBackgroundDataSetting(boolean allowBackgroundData) {
455        try {
456            mService.setBackgroundDataSetting(allowBackgroundData);
457        } catch (RemoteException e) {
458        }
459    }
460
461    /**
462     * Gets the value of the setting for enabling Mobile data.
463     *
464     * @return Whether mobile data is enabled.
465     * @hide
466     */
467    public boolean getMobileDataEnabled() {
468        try {
469            return mService.getMobileDataEnabled();
470        } catch (RemoteException e) {
471            return true;
472        }
473    }
474
475    /**
476     * Sets the persisted value for enabling/disabling Mobile data.
477     *
478     * @param enabled Whether the mobile data connection should be
479     *            used or not.
480     * @hide
481     */
482    public void setMobileDataEnabled(boolean enabled) {
483        try {
484            mService.setMobileDataEnabled(enabled);
485        } catch (RemoteException e) {
486        }
487    }
488
489    /**
490     * {@hide}
491     */
492    public ConnectivityManager(IConnectivityManager service) {
493        if (service == null) {
494            throw new IllegalArgumentException("missing IConnectivityManager");
495        }
496        mService = service;
497    }
498
499    /**
500     * {@hide}
501     */
502    public String[] getTetherableIfaces() {
503        try {
504            return mService.getTetherableIfaces();
505        } catch (RemoteException e) {
506            return new String[0];
507        }
508    }
509
510    /**
511     * {@hide}
512     */
513    public String[] getTetheredIfaces() {
514        try {
515            return mService.getTetheredIfaces();
516        } catch (RemoteException e) {
517            return new String[0];
518        }
519    }
520
521    /**
522     * {@hide}
523     */
524    public String[] getTetheringErroredIfaces() {
525        try {
526            return mService.getTetheringErroredIfaces();
527        } catch (RemoteException e) {
528            return new String[0];
529        }
530    }
531
532    /**
533     * @return error A TETHER_ERROR value indicating success or failure type
534     * {@hide}
535     */
536    public int tether(String iface) {
537        try {
538            return mService.tether(iface);
539        } catch (RemoteException e) {
540            return TETHER_ERROR_SERVICE_UNAVAIL;
541        }
542    }
543
544    /**
545     * @return error A TETHER_ERROR value indicating success or failure type
546     * {@hide}
547     */
548    public int untether(String iface) {
549        try {
550            return mService.untether(iface);
551        } catch (RemoteException e) {
552            return TETHER_ERROR_SERVICE_UNAVAIL;
553        }
554    }
555
556    /**
557     * {@hide}
558     */
559    public boolean isTetheringSupported() {
560        try {
561            return mService.isTetheringSupported();
562        } catch (RemoteException e) {
563            return false;
564        }
565    }
566
567    /**
568     * {@hide}
569     */
570    public String[] getTetherableUsbRegexs() {
571        try {
572            return mService.getTetherableUsbRegexs();
573        } catch (RemoteException e) {
574            return new String[0];
575        }
576    }
577
578    /**
579     * {@hide}
580     */
581    public String[] getTetherableWifiRegexs() {
582        try {
583            return mService.getTetherableWifiRegexs();
584        } catch (RemoteException e) {
585            return new String[0];
586        }
587    }
588
589    /**
590     * {@hide}
591     */
592    public String[] getTetherableBluetoothRegexs() {
593        try {
594            return mService.getTetherableBluetoothRegexs();
595        } catch (RemoteException e) {
596            return new String[0];
597        }
598    }
599
600    /** {@hide} */
601    public static final int TETHER_ERROR_NO_ERROR           = 0;
602    /** {@hide} */
603    public static final int TETHER_ERROR_UNKNOWN_IFACE      = 1;
604    /** {@hide} */
605    public static final int TETHER_ERROR_SERVICE_UNAVAIL    = 2;
606    /** {@hide} */
607    public static final int TETHER_ERROR_UNSUPPORTED        = 3;
608    /** {@hide} */
609    public static final int TETHER_ERROR_UNAVAIL_IFACE      = 4;
610    /** {@hide} */
611    public static final int TETHER_ERROR_MASTER_ERROR       = 5;
612    /** {@hide} */
613    public static final int TETHER_ERROR_TETHER_IFACE_ERROR = 6;
614    /** {@hide} */
615    public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR = 7;
616    /** {@hide} */
617    public static final int TETHER_ERROR_ENABLE_NAT_ERROR     = 8;
618    /** {@hide} */
619    public static final int TETHER_ERROR_DISABLE_NAT_ERROR    = 9;
620    /** {@hide} */
621    public static final int TETHER_ERROR_IFACE_CFG_ERROR      = 10;
622
623    /**
624     * @param iface The name of the interface we're interested in
625     * @return error The error code of the last error tethering or untethering the named
626     *               interface
627     * {@hide}
628     */
629    public int getLastTetherError(String iface) {
630        try {
631            return mService.getLastTetherError(iface);
632        } catch (RemoteException e) {
633            return TETHER_ERROR_SERVICE_UNAVAIL;
634        }
635    }
636
637    /**
638     * Ensure the device stays awake until we connect with the next network
639     * @param forWhome The name of the network going down for logging purposes
640     * @return {@code true} on success, {@code false} on failure
641     * {@hide}
642     */
643    public boolean requestNetworkTransitionWakelock(String forWhom) {
644        try {
645            mService.requestNetworkTransitionWakelock(forWhom);
646            return true;
647        } catch (RemoteException e) {
648            return false;
649        }
650    }
651
652    /**
653     * @param networkType The type of network you want to report on
654     * @param percentage The quality of the connection 0 is bad, 100 is good
655     * {@hide}
656     */
657    public void reportInetCondition(int networkType, int percentage) {
658        try {
659            mService.reportInetCondition(networkType, percentage);
660        } catch (RemoteException e) {
661        }
662    }
663
664    /**
665     * @param proxyProperties The definition for the new global http proxy
666     * {@hide}
667     */
668    public void setGlobalProxy(ProxyProperties p) {
669        try {
670            mService.setGlobalProxy(p);
671        } catch (RemoteException e) {
672        }
673    }
674
675    /**
676     * @return proxyProperties for the current global proxy
677     * {@hide}
678     */
679    public ProxyProperties getGlobalProxy() {
680        try {
681            return mService.getGlobalProxy();
682        } catch (RemoteException e) {
683            return null;
684        }
685    }
686
687    /**
688     * @return proxyProperties for the current proxy (global if set, network specific if not)
689     * {@hide}
690     */
691    public ProxyProperties getProxy() {
692        try {
693            return mService.getProxy();
694        } catch (RemoteException e) {
695            return null;
696        }
697    }
698
699    /**
700     * @param networkType The network who's dependence has changed
701     * @param met Boolean - true if network use is ok, false if not
702     * {@hide}
703     */
704    public void setDataDependency(int networkType, boolean met) {
705        try {
706            mService.setDataDependency(networkType, met);
707        } catch (RemoteException e) {
708        }
709    }
710}
711