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