ConnectivityManager.java revision 1e9aac2bd855f12708d3049eff4435fa4a2f4317
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
24/**
25 * Class that answers queries about the state of network connectivity. It also
26 * notifies applications when network connectivity changes. Get an instance
27 * of this class by calling
28 * {@link android.content.Context#getSystemService(String) Context.getSystemService(Context.CONNECTIVITY_SERVICE)}.
29 * <p>
30 * The primary responsibilities of this class are to:
31 * <ol>
32 * <li>Monitor network connections (Wi-Fi, GPRS, UMTS, etc.)</li>
33 * <li>Send broadcast intents when network connectivity changes</li>
34 * <li>Attempt to "fail over" to another network when connectivity to a network
35 * is lost</li>
36 * <li>Provide an API that allows applications to query the coarse-grained or fine-grained
37 * state of the available networks</li>
38 * </ol>
39 */
40public class ConnectivityManager
41{
42    /**
43     * A change in network connectivity has occurred. A connection has either
44     * been established or lost. The NetworkInfo for the affected network is
45     * sent as an extra; it should be consulted to see what kind of
46     * connectivity event occurred.
47     * <p/>
48     * If this is a connection that was the result of failing over from a
49     * disconnected network, then the FAILOVER_CONNECTION boolean extra is
50     * set to true.
51     * <p/>
52     * For a loss of connectivity, if the connectivity manager is attempting
53     * to connect (or has already connected) to another network, the
54     * NetworkInfo for the new network is also passed as an extra. This lets
55     * any receivers of the broadcast know that they should not necessarily
56     * tell the user that no data traffic will be possible. Instead, the
57     * reciever should expect another broadcast soon, indicating either that
58     * the failover attempt succeeded (and so there is still overall data
59     * connectivity), or that the failover attempt failed, meaning that all
60     * connectivity has been lost.
61     * <p/>
62     * For a disconnect event, the boolean extra EXTRA_NO_CONNECTIVITY
63     * is set to {@code true} if there are no connected networks at all.
64     */
65    public static final String CONNECTIVITY_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
66    /**
67     * The lookup key for a {@link NetworkInfo} object. Retrieve with
68     * {@link android.content.Intent#getParcelableExtra(String)}.
69     */
70    public static final String EXTRA_NETWORK_INFO = "networkInfo";
71    /**
72     * The lookup key for a boolean that indicates whether a connect event
73     * is for a network to which the connectivity manager was failing over
74     * following a disconnect on another network.
75     * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
76     */
77    public static final String EXTRA_IS_FAILOVER = "isFailover";
78    /**
79     * The lookup key for a {@link NetworkInfo} object. This is supplied when
80     * there is another network that it may be possible to connect to. Retrieve with
81     * {@link android.content.Intent#getParcelableExtra(String)}.
82     */
83    public static final String EXTRA_OTHER_NETWORK_INFO = "otherNetwork";
84    /**
85     * The lookup key for a boolean that indicates whether there is a
86     * complete lack of connectivity, i.e., no network is available.
87     * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
88     */
89    public static final String EXTRA_NO_CONNECTIVITY = "noConnectivity";
90    /**
91     * The lookup key for a string that indicates why an attempt to connect
92     * to a network failed. The string has no particular structure. It is
93     * intended to be used in notifications presented to users. Retrieve
94     * it with {@link android.content.Intent#getStringExtra(String)}.
95     */
96    public static final String EXTRA_REASON = "reason";
97    /**
98     * The lookup key for a string that provides optionally supplied
99     * extra information about the network state. The information
100     * may be passed up from the lower networking layers, and its
101     * meaning may be specific to a particular network type. Retrieve
102     * it with {@link android.content.Intent#getStringExtra(String)}.
103     */
104    public static final String EXTRA_EXTRA_INFO = "extraInfo";
105    /**
106     * The lookup key for an int that provides information about
107     * our connection to the internet at large.  0 indicates no connection,
108     * 100 indicates a great connection.  Retrieve it with
109     * {@link android.content.Intent@getIntExtra(String)}.
110     * {@hide}
111     */
112    public static final String EXTRA_INET_CONDITION = "inetCondition";
113
114    /**
115     * Broadcast Action: The setting for background data usage has changed
116     * values. Use {@link #getBackgroundDataSetting()} to get the current value.
117     * <p>
118     * If an application uses the network in the background, it should listen
119     * for this broadcast and stop using the background data if the value is
120     * false.
121     */
122    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
123    public static final String ACTION_BACKGROUND_DATA_SETTING_CHANGED =
124            "android.net.conn.BACKGROUND_DATA_SETTING_CHANGED";
125
126
127    /**
128     * Broadcast Action: The network connection may not be good
129     * uses {@code ConnectivityManager.EXTRA_INET_CONDITION} and
130     * {@code ConnectivityManager.EXTRA_NETWORK_INFO} to specify
131     * the network and it's condition.
132     * @hide
133     */
134    public static final String INET_CONDITION_ACTION =
135            "android.net.conn.INET_CONDITION_ACTION";
136
137    /**
138     * Broadcast Action: A tetherable connection has come or gone
139     * TODO - finish the doc
140     * @hide
141     */
142    public static final String ACTION_TETHER_STATE_CHANGED =
143            "android.net.conn.TETHER_STATE_CHANGED";
144
145    /**
146     * @hide
147     * gives a String[]
148     */
149    public static final String EXTRA_AVAILABLE_TETHER = "availableArray";
150
151    /**
152     * @hide
153     * gives a String[]
154     */
155    public static final String EXTRA_ACTIVE_TETHER = "activeArray";
156
157    /**
158     * @hide
159     * gives a String[]
160     */
161    public static final String EXTRA_ERRORED_TETHER = "erroredArray";
162
163    /**
164     * The Default Mobile data connection.  When active, all data traffic
165     * will use this connection by default.  Should not coexist with other
166     * default connections.
167     */
168    public static final int TYPE_MOBILE      = 0;
169    /**
170     * The Default WIFI data connection.  When active, all data traffic
171     * will use this connection by default.  Should not coexist with other
172     * default connections.
173     */
174    public static final int TYPE_WIFI        = 1;
175    /**
176     * An MMS-specific Mobile data connection.  This connection may be the
177     * same as {@link #TYPE_MOBILE} but it may be different.  This is used
178     * by applications needing to talk to the carrier's Multimedia Messaging
179     * Service servers.  It may coexist with default data connections.
180     */
181    public static final int TYPE_MOBILE_MMS  = 2;
182    /**
183     * A SUPL-specific Mobile data connection.  This connection may be the
184     * same as {@link #TYPE_MOBILE} but it may be different.  This is used
185     * by applications needing to talk to the carrier's Secure User Plane
186     * Location servers for help locating the device.  It may coexist with
187     * default data connections.
188     */
189    public static final int TYPE_MOBILE_SUPL = 3;
190    /**
191     * A DUN-specific Mobile data connection.  This connection may be the
192     * same as {@link #TYPE_MOBILE} but it may be different.  This is used
193     * by applicaitons performing a Dial Up Networking bridge so that
194     * the carrier is aware of DUN traffic.  It may coexist with default data
195     * connections.
196     */
197    public static final int TYPE_MOBILE_DUN  = 4;
198    /**
199     * A High Priority Mobile data connection.  This connection is typically
200     * the same as {@link #TYPE_MOBILE} but the routing setup is different.
201     * Only requesting processes will have access to the Mobile DNS servers
202     * and only IP's explicitly requested via {@link #requestRouteToHost}
203     * will route over this interface if a default route exists.
204     */
205    public static final int TYPE_MOBILE_HIPRI = 5;
206    /**
207     * The Default WiMAX data connection.  When active, all data traffic
208     * will use this connection by default.  Should not coexist with other
209     * default connections.
210     */
211    public static final int TYPE_WIMAX       = 6;
212    /** {@hide} TODO: Need to adjust this for WiMAX. */
213    public static final int MAX_RADIO_TYPE   = TYPE_WIFI;
214    /** {@hide} TODO: Need to adjust this for WiMAX. */
215    public static final int MAX_NETWORK_TYPE = TYPE_MOBILE_HIPRI;
216
217    public static final int DEFAULT_NETWORK_PREFERENCE = TYPE_WIFI;
218
219    private IConnectivityManager mService;
220
221    static public boolean isNetworkTypeValid(int networkType) {
222        return networkType >= 0 && networkType <= MAX_NETWORK_TYPE;
223    }
224
225    public void setNetworkPreference(int preference) {
226        try {
227            mService.setNetworkPreference(preference);
228        } catch (RemoteException e) {
229        }
230    }
231
232    public int getNetworkPreference() {
233        try {
234            return mService.getNetworkPreference();
235        } catch (RemoteException e) {
236            return -1;
237        }
238    }
239
240    public NetworkInfo getActiveNetworkInfo() {
241        try {
242            return mService.getActiveNetworkInfo();
243        } catch (RemoteException e) {
244            return null;
245        }
246    }
247
248    public NetworkInfo getNetworkInfo(int networkType) {
249        try {
250            return mService.getNetworkInfo(networkType);
251        } catch (RemoteException e) {
252            return null;
253        }
254    }
255
256    public NetworkInfo[] getAllNetworkInfo() {
257        try {
258            return mService.getAllNetworkInfo();
259        } catch (RemoteException e) {
260            return null;
261        }
262    }
263
264    /** {@hide} */
265    public boolean setRadios(boolean turnOn) {
266        try {
267            return mService.setRadios(turnOn);
268        } catch (RemoteException e) {
269            return false;
270        }
271    }
272
273    /** {@hide} */
274    public boolean setRadio(int networkType, boolean turnOn) {
275        try {
276            return mService.setRadio(networkType, turnOn);
277        } catch (RemoteException e) {
278            return false;
279        }
280    }
281
282    /**
283     * Tells the underlying networking system that the caller wants to
284     * begin using the named feature. The interpretation of {@code feature}
285     * is completely up to each networking implementation.
286     * @param networkType specifies which network the request pertains to
287     * @param feature the name of the feature to be used
288     * @return an integer value representing the outcome of the request.
289     * The interpretation of this value is specific to each networking
290     * implementation+feature combination, except that the value {@code -1}
291     * always indicates failure.
292     */
293    public int startUsingNetworkFeature(int networkType, String feature) {
294        try {
295            return mService.startUsingNetworkFeature(networkType, feature,
296                    new Binder());
297        } catch (RemoteException e) {
298            return -1;
299        }
300    }
301
302    /**
303     * Tells the underlying networking system that the caller is finished
304     * using the named feature. The interpretation of {@code feature}
305     * is completely up to each networking implementation.
306     * @param networkType specifies which network the request pertains to
307     * @param feature the name of the feature that is no longer needed
308     * @return an integer value representing the outcome of the request.
309     * The interpretation of this value is specific to each networking
310     * implementation+feature combination, except that the value {@code -1}
311     * always indicates failure.
312     */
313    public int stopUsingNetworkFeature(int networkType, String feature) {
314        try {
315            return mService.stopUsingNetworkFeature(networkType, feature);
316        } catch (RemoteException e) {
317            return -1;
318        }
319    }
320
321    /**
322     * Ensure that a network route exists to deliver traffic to the specified
323     * host via the specified network interface. An attempt to add a route that
324     * already exists is ignored, but treated as successful.
325     * @param networkType the type of the network over which traffic to the specified
326     * host is to be routed
327     * @param hostAddress the IP address of the host to which the route is desired
328     * @return {@code true} on success, {@code false} on failure
329     */
330    public boolean requestRouteToHost(int networkType, int hostAddress) {
331        try {
332            return mService.requestRouteToHost(networkType, hostAddress);
333        } catch (RemoteException e) {
334            return false;
335        }
336    }
337
338    /**
339     * Returns the value of the setting for background data usage. If false,
340     * applications should not use the network if the application is not in the
341     * foreground. Developers should respect this setting, and check the value
342     * of this before performing any background data operations.
343     * <p>
344     * All applications that have background services that use the network
345     * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
346     *
347     * @return Whether background data usage is allowed.
348     */
349    public boolean getBackgroundDataSetting() {
350        try {
351            return mService.getBackgroundDataSetting();
352        } catch (RemoteException e) {
353            // Err on the side of safety
354            return false;
355        }
356    }
357
358    /**
359     * Sets the value of the setting for background data usage.
360     *
361     * @param allowBackgroundData Whether an application should use data while
362     *            it is in the background.
363     *
364     * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
365     * @see #getBackgroundDataSetting()
366     * @hide
367     */
368    public void setBackgroundDataSetting(boolean allowBackgroundData) {
369        try {
370            mService.setBackgroundDataSetting(allowBackgroundData);
371        } catch (RemoteException e) {
372        }
373    }
374
375    /**
376     * Gets the value of the setting for enabling Mobile data.
377     *
378     * @return Whether mobile data is enabled.
379     * @hide
380     */
381    public boolean getMobileDataEnabled() {
382        try {
383            return mService.getMobileDataEnabled();
384        } catch (RemoteException e) {
385            return true;
386        }
387    }
388
389    /**
390     * Sets the persisted value for enabling/disabling Mobile data.
391     *
392     * @param enabled Whether the mobile data connection should be
393     *            used or not.
394     * @hide
395     */
396    public void setMobileDataEnabled(boolean enabled) {
397        try {
398            mService.setMobileDataEnabled(enabled);
399        } catch (RemoteException e) {
400        }
401    }
402
403    /**
404     * Don't allow use of default constructor.
405     */
406    @SuppressWarnings({"UnusedDeclaration"})
407    private ConnectivityManager() {
408    }
409
410    /**
411     * {@hide}
412     */
413    public ConnectivityManager(IConnectivityManager service) {
414        if (service == null) {
415            throw new IllegalArgumentException(
416                "ConnectivityManager() cannot be constructed with null service");
417        }
418        mService = service;
419    }
420
421    /**
422     * {@hide}
423     */
424    public String[] getTetherableIfaces() {
425        try {
426            return mService.getTetherableIfaces();
427        } catch (RemoteException e) {
428            return new String[0];
429        }
430    }
431
432    /**
433     * {@hide}
434     */
435    public String[] getTetheredIfaces() {
436        try {
437            return mService.getTetheredIfaces();
438        } catch (RemoteException e) {
439            return new String[0];
440        }
441    }
442
443    /**
444     * {@hide}
445     */
446    public String[] getTetheringErroredIfaces() {
447        try {
448            return mService.getTetheringErroredIfaces();
449        } catch (RemoteException e) {
450            return new String[0];
451        }
452    }
453
454    /**
455     * @return error A TETHER_ERROR value indicating success or failure type
456     * {@hide}
457     */
458    public int tether(String iface) {
459        try {
460            return mService.tether(iface);
461        } catch (RemoteException e) {
462            return TETHER_ERROR_SERVICE_UNAVAIL;
463        }
464    }
465
466    /**
467     * @return error A TETHER_ERROR value indicating success or failure type
468     * {@hide}
469     */
470    public int untether(String iface) {
471        try {
472            return mService.untether(iface);
473        } catch (RemoteException e) {
474            return TETHER_ERROR_SERVICE_UNAVAIL;
475        }
476    }
477
478    /**
479     * {@hide}
480     */
481    public boolean isTetheringSupported() {
482        try {
483            return mService.isTetheringSupported();
484        } catch (RemoteException e) {
485            return false;
486        }
487    }
488
489    /**
490     * {@hide}
491     */
492    public String[] getTetherableUsbRegexs() {
493        try {
494            return mService.getTetherableUsbRegexs();
495        } catch (RemoteException e) {
496            return new String[0];
497        }
498    }
499
500    /**
501     * {@hide}
502     */
503    public String[] getTetherableWifiRegexs() {
504        try {
505            return mService.getTetherableWifiRegexs();
506        } catch (RemoteException e) {
507            return new String[0];
508        }
509    }
510
511    /** {@hide} */
512    public static final int TETHER_ERROR_NO_ERROR           = 0;
513    /** {@hide} */
514    public static final int TETHER_ERROR_UNKNOWN_IFACE      = 1;
515    /** {@hide} */
516    public static final int TETHER_ERROR_SERVICE_UNAVAIL    = 2;
517    /** {@hide} */
518    public static final int TETHER_ERROR_UNSUPPORTED        = 3;
519    /** {@hide} */
520    public static final int TETHER_ERROR_UNAVAIL_IFACE      = 4;
521    /** {@hide} */
522    public static final int TETHER_ERROR_MASTER_ERROR       = 5;
523    /** {@hide} */
524    public static final int TETHER_ERROR_TETHER_IFACE_ERROR = 6;
525    /** {@hide} */
526    public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR = 7;
527    /** {@hide} */
528    public static final int TETHER_ERROR_ENABLE_NAT_ERROR     = 8;
529    /** {@hide} */
530    public static final int TETHER_ERROR_DISABLE_NAT_ERROR    = 9;
531    /** {@hide} */
532    public static final int TETHER_ERROR_IFACE_CFG_ERROR      = 10;
533
534    /**
535     * @param iface The name of the interface we're interested in
536     * @return error The error code of the last error tethering or untethering the named
537     *               interface
538     * {@hide}
539     */
540    public int getLastTetherError(String iface) {
541        try {
542            return mService.getLastTetherError(iface);
543        } catch (RemoteException e) {
544            return TETHER_ERROR_SERVICE_UNAVAIL;
545        }
546    }
547
548    /**
549     * @param networkType The type of network you want to report on
550     * @param percentage The quality of the connection 0 is bad, 100 is good
551     * {@hide}
552     */
553    public void reportInetCondition(int networkType, int percentage) {
554        try {
555            mService.reportInetCondition(networkType, percentage);
556        } catch (RemoteException e) {
557        }
558    }
559}
560