blob: 09ea8f9b876da084bceee3a2e9f157c1bf1376b4 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
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 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080016package android.net;
17
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070018import static com.android.internal.util.Preconditions.checkNotNull;
Jeremy Klein36c7aa02016-01-22 14:11:45 -080019
Felipe Leme1b103232016-01-22 09:44:57 -080020import android.annotation.IntDef;
Robin Lee244ce8e2016-01-05 18:03:46 +000021import android.annotation.Nullable;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022import android.annotation.SdkConstant;
23import android.annotation.SdkConstant.SdkConstantType;
Udam Sainib7c24872016-01-04 12:16:14 -080024import android.annotation.SystemApi;
Robert Greenwalt9258c642014-03-26 16:47:06 -070025import android.app.PendingIntent;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -070026import android.content.Context;
Robert Greenwaltd19c41c2014-05-18 23:07:25 -070027import android.content.Intent;
Lorenzo Colittiffc42b02015-07-29 11:41:21 +090028import android.content.pm.PackageManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -070029import android.os.Binder;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -070030import android.os.Build.VERSION_CODES;
Jeremy Klein36c7aa02016-01-22 14:11:45 -080031import android.os.Bundle;
Robert Greenwalt9258c642014-03-26 16:47:06 -070032import android.os.Handler;
33import android.os.HandlerThread;
Dianne Hackborn77b987f2014-02-26 16:20:52 -080034import android.os.IBinder;
35import android.os.INetworkActivityListener;
36import android.os.INetworkManagementService;
Robert Greenwalt9258c642014-03-26 16:47:06 -070037import android.os.Looper;
38import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070039import android.os.Messenger;
Lorenzo Colittiffc42b02015-07-29 11:41:21 +090040import android.os.Process;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -080042import android.os.ResultReceiver;
Dianne Hackborn77b987f2014-02-26 16:20:52 -080043import android.os.ServiceManager;
Jeff Sharkey961e3042011-08-29 16:02:57 -070044import android.provider.Settings;
Wink Saville36ffb042014-12-05 11:10:30 -080045import android.telephony.SubscriptionManager;
Dianne Hackborn77b987f2014-02-26 16:20:52 -080046import android.util.ArrayMap;
Robert Greenwalt9258c642014-03-26 16:47:06 -070047import android.util.Log;
Lorenzo Colittifcfa7d92016-03-01 22:56:37 +090048import android.util.SparseArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049
Robert Greenwaltafa05c02014-05-21 20:04:36 -070050import com.android.internal.telephony.ITelephony;
Robert Greenwalt562cc542014-05-15 18:07:26 -070051import com.android.internal.telephony.PhoneConstants;
Robert Greenwaltafa05c02014-05-21 20:04:36 -070052import com.android.internal.util.Protocol;
Lorenzo Colittifcfa7d92016-03-01 22:56:37 +090053import com.android.internal.util.MessageUtils;
Robert Greenwaltafa05c02014-05-21 20:04:36 -070054
Paul Jensenc91b5342014-08-27 12:38:45 -040055import libcore.net.event.NetworkEventDispatcher;
56
Felipe Leme1b103232016-01-22 09:44:57 -080057import java.lang.annotation.Retention;
58import java.lang.annotation.RetentionPolicy;
Jeremy Kleind42209d2015-12-28 15:11:58 -080059import java.net.InetAddress;
60import java.util.HashMap;
61import java.util.concurrent.atomic.AtomicInteger;
62
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063/**
64 * Class that answers queries about the state of network connectivity. It also
65 * notifies applications when network connectivity changes. Get an instance
66 * of this class by calling
67 * {@link android.content.Context#getSystemService(String) Context.getSystemService(Context.CONNECTIVITY_SERVICE)}.
68 * <p>
69 * The primary responsibilities of this class are to:
70 * <ol>
71 * <li>Monitor network connections (Wi-Fi, GPRS, UMTS, etc.)</li>
72 * <li>Send broadcast intents when network connectivity changes</li>
73 * <li>Attempt to "fail over" to another network when connectivity to a network
74 * is lost</li>
75 * <li>Provide an API that allows applications to query the coarse-grained or fine-grained
76 * state of the available networks</li>
Robert Greenwaltd19c41c2014-05-18 23:07:25 -070077 * <li>Provide an API that allows applications to request and select networks for their data
78 * traffic</li>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080079 * </ol>
80 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070081public class ConnectivityManager {
82 private static final String TAG = "ConnectivityManager";
83
Lorenzo Colittifcfa7d92016-03-01 22:56:37 +090084 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
85 new Class[]{ConnectivityManager.class}, new String[]{"CALLBACK_"});
86
87 private static final String whatToString(int what) {
88 return sMagicDecoderRing.get(what, Integer.toString(what));
89 }
90
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091 /**
Robert Greenwaltd19c41c2014-05-18 23:07:25 -070092 * A change in network connectivity has occurred. A default connection has either
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093 * been established or lost. The NetworkInfo for the affected network is
94 * sent as an extra; it should be consulted to see what kind of
95 * connectivity event occurred.
96 * <p/>
97 * If this is a connection that was the result of failing over from a
98 * disconnected network, then the FAILOVER_CONNECTION boolean extra is
99 * set to true.
100 * <p/>
101 * For a loss of connectivity, if the connectivity manager is attempting
102 * to connect (or has already connected) to another network, the
103 * NetworkInfo for the new network is also passed as an extra. This lets
104 * any receivers of the broadcast know that they should not necessarily
105 * tell the user that no data traffic will be possible. Instead, the
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800106 * receiver should expect another broadcast soon, indicating either that
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107 * the failover attempt succeeded (and so there is still overall data
108 * connectivity), or that the failover attempt failed, meaning that all
109 * connectivity has been lost.
110 * <p/>
111 * For a disconnect event, the boolean extra EXTRA_NO_CONNECTIVITY
112 * is set to {@code true} if there are no connected networks at all.
113 */
Jeff Sharkey4fa63b22013-02-20 18:21:19 -0800114 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115 public static final String CONNECTIVITY_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700116
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117 /**
Robert Greenwalte94a6ff2015-09-01 08:23:04 -0700118 * A temporary hack until SUPL system can get off the legacy APIS.
119 * They do too many network requests and the long list of apps listening
120 * and waking due to the CONNECTIVITY_ACTION bcast makes it expensive.
121 * Use this bcast intent instead for SUPL requests.
122 * @hide
123 */
124 public static final String CONNECTIVITY_ACTION_SUPL =
125 "android.net.conn.CONNECTIVITY_CHANGE_SUPL";
126
127 /**
Paul Jensen25a217c2015-02-27 22:55:47 -0500128 * The device has connected to a network that has presented a captive
129 * portal, which is blocking Internet connectivity. The user was presented
130 * with a notification that network sign in is required,
131 * and the user invoked the notification's action indicating they
Paul Jensen49e3edf2015-05-22 10:50:39 -0400132 * desire to sign in to the network. Apps handling this activity should
Paul Jensen25a217c2015-02-27 22:55:47 -0500133 * facilitate signing in to the network. This action includes a
134 * {@link Network} typed extra called {@link #EXTRA_NETWORK} that represents
135 * the network presenting the captive portal; all communication with the
136 * captive portal must be done using this {@code Network} object.
137 * <p/>
Paul Jensen49e3edf2015-05-22 10:50:39 -0400138 * This activity includes a {@link CaptivePortal} extra named
139 * {@link #EXTRA_CAPTIVE_PORTAL} that can be used to indicate different
140 * outcomes of the captive portal sign in to the system:
141 * <ul>
142 * <li> When the app handling this action believes the user has signed in to
143 * the network and the captive portal has been dismissed, the app should
144 * call {@link CaptivePortal#reportCaptivePortalDismissed} so the system can
145 * reevaluate the network. If reevaluation finds the network no longer
146 * subject to a captive portal, the network may become the default active
147 * data network. </li>
148 * <li> When the app handling this action believes the user explicitly wants
Paul Jensen25a217c2015-02-27 22:55:47 -0500149 * to ignore the captive portal and the network, the app should call
Paul Jensen49e3edf2015-05-22 10:50:39 -0400150 * {@link CaptivePortal#ignoreNetwork}. </li>
151 * </ul>
Paul Jensen25a217c2015-02-27 22:55:47 -0500152 */
153 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
154 public static final String ACTION_CAPTIVE_PORTAL_SIGN_IN = "android.net.conn.CAPTIVE_PORTAL";
155
156 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800157 * The lookup key for a {@link NetworkInfo} object. Retrieve with
158 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700159 *
160 * @deprecated Since {@link NetworkInfo} can vary based on UID, applications
161 * should always obtain network information through
Paul Jensen3541e9f2015-03-18 12:23:02 -0400162 * {@link #getActiveNetworkInfo()}.
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -0700163 * @see #EXTRA_NETWORK_TYPE
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800164 */
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700165 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800166 public static final String EXTRA_NETWORK_INFO = "networkInfo";
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700167
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800168 /**
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -0700169 * Network type which triggered a {@link #CONNECTIVITY_ACTION} broadcast.
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -0700170 *
171 * @see android.content.Intent#getIntExtra(String, int)
172 */
173 public static final String EXTRA_NETWORK_TYPE = "networkType";
174
175 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800176 * The lookup key for a boolean that indicates whether a connect event
177 * is for a network to which the connectivity manager was failing over
178 * following a disconnect on another network.
179 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
180 */
181 public static final String EXTRA_IS_FAILOVER = "isFailover";
182 /**
183 * The lookup key for a {@link NetworkInfo} object. This is supplied when
184 * there is another network that it may be possible to connect to. Retrieve with
185 * {@link android.content.Intent#getParcelableExtra(String)}.
186 */
187 public static final String EXTRA_OTHER_NETWORK_INFO = "otherNetwork";
188 /**
189 * The lookup key for a boolean that indicates whether there is a
190 * complete lack of connectivity, i.e., no network is available.
191 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
192 */
193 public static final String EXTRA_NO_CONNECTIVITY = "noConnectivity";
194 /**
195 * The lookup key for a string that indicates why an attempt to connect
196 * to a network failed. The string has no particular structure. It is
197 * intended to be used in notifications presented to users. Retrieve
198 * it with {@link android.content.Intent#getStringExtra(String)}.
199 */
200 public static final String EXTRA_REASON = "reason";
201 /**
202 * The lookup key for a string that provides optionally supplied
203 * extra information about the network state. The information
204 * may be passed up from the lower networking layers, and its
205 * meaning may be specific to a particular network type. Retrieve
206 * it with {@link android.content.Intent#getStringExtra(String)}.
207 */
208 public static final String EXTRA_EXTRA_INFO = "extraInfo";
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700209 /**
210 * The lookup key for an int that provides information about
211 * our connection to the internet at large. 0 indicates no connection,
212 * 100 indicates a great connection. Retrieve it with
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700213 * {@link android.content.Intent#getIntExtra(String, int)}.
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700214 * {@hide}
215 */
216 public static final String EXTRA_INET_CONDITION = "inetCondition";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800217 /**
Paul Jensen49e3edf2015-05-22 10:50:39 -0400218 * The lookup key for a {@link CaptivePortal} object included with the
219 * {@link #ACTION_CAPTIVE_PORTAL_SIGN_IN} intent. The {@code CaptivePortal}
220 * object can be used to either indicate to the system that the captive
221 * portal has been dismissed or that the user does not want to pursue
222 * signing in to captive portal. Retrieve it with
223 * {@link android.content.Intent#getParcelableExtra(String)}.
Paul Jensen25a217c2015-02-27 22:55:47 -0500224 */
Paul Jensen49e3edf2015-05-22 10:50:39 -0400225 public static final String EXTRA_CAPTIVE_PORTAL = "android.net.extra.CAPTIVE_PORTAL";
Jan Nordqvist52eb29f2015-09-22 15:54:32 -0700226
227 /**
228 * Key for passing a URL to the captive portal login activity.
229 */
230 public static final String EXTRA_CAPTIVE_PORTAL_URL = "android.net.extra.CAPTIVE_PORTAL_URL";
231
Paul Jensen25a217c2015-02-27 22:55:47 -0500232 /**
Haoyu Baidb3c8672012-06-20 14:29:57 -0700233 * Broadcast action to indicate the change of data activity status
234 * (idle or active) on a network in a recent period.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800235 * The network becomes active when data transmission is started, or
236 * idle if there is no data transmission for a period of time.
Haoyu Baidb3c8672012-06-20 14:29:57 -0700237 * {@hide}
238 */
239 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
240 public static final String ACTION_DATA_ACTIVITY_CHANGE = "android.net.conn.DATA_ACTIVITY_CHANGE";
241 /**
242 * The lookup key for an enum that indicates the network device type on which this data activity
243 * change happens.
244 * {@hide}
245 */
246 public static final String EXTRA_DEVICE_TYPE = "deviceType";
247 /**
248 * The lookup key for a boolean that indicates the device is active or not. {@code true} means
249 * it is actively sending or receiving data and {@code false} means it is idle.
250 * {@hide}
251 */
252 public static final String EXTRA_IS_ACTIVE = "isActive";
Ashish Sharma0535a9f2014-03-12 18:42:23 -0700253 /**
254 * The lookup key for a long that contains the timestamp (nanos) of the radio state change.
255 * {@hide}
256 */
257 public static final String EXTRA_REALTIME_NS = "tsNanos";
Haoyu Baidb3c8672012-06-20 14:29:57 -0700258
259 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800260 * Broadcast Action: The setting for background data usage has changed
261 * values. Use {@link #getBackgroundDataSetting()} to get the current value.
262 * <p>
263 * If an application uses the network in the background, it should listen
264 * for this broadcast and stop using the background data if the value is
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700265 * {@code false}.
Jeff Sharkey54ee2ad2012-01-30 16:29:24 -0800266 * <p>
267 *
268 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability
269 * of background data depends on several combined factors, and
270 * this broadcast is no longer sent. Instead, when background
271 * data is unavailable, {@link #getActiveNetworkInfo()} will now
272 * appear disconnected. During first boot after a platform
273 * upgrade, this broadcast will be sent once if
274 * {@link #getBackgroundDataSetting()} was {@code false} before
275 * the upgrade.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800276 */
277 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Jeff Sharkey54ee2ad2012-01-30 16:29:24 -0800278 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800279 public static final String ACTION_BACKGROUND_DATA_SETTING_CHANGED =
280 "android.net.conn.BACKGROUND_DATA_SETTING_CHANGED";
281
Robert Greenwalt1e9aac22010-09-15 17:36:33 -0700282 /**
283 * Broadcast Action: The network connection may not be good
284 * uses {@code ConnectivityManager.EXTRA_INET_CONDITION} and
285 * {@code ConnectivityManager.EXTRA_NETWORK_INFO} to specify
286 * the network and it's condition.
287 * @hide
288 */
Jeff Sharkey4fa63b22013-02-20 18:21:19 -0800289 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Robert Greenwalt1e9aac22010-09-15 17:36:33 -0700290 public static final String INET_CONDITION_ACTION =
291 "android.net.conn.INET_CONDITION_ACTION";
292
Robert Greenwalt42acef32009-08-12 16:08:25 -0700293 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800294 * Broadcast Action: A tetherable connection has come or gone.
295 * Uses {@code ConnectivityManager.EXTRA_AVAILABLE_TETHER},
296 * {@code ConnectivityManager.EXTRA_ACTIVE_TETHER} and
297 * {@code ConnectivityManager.EXTRA_ERRORED_TETHER} to indicate
298 * the current state of tethering. Each include a list of
299 * interface names in that state (may be empty).
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800300 * @hide
301 */
Jeff Sharkey4fa63b22013-02-20 18:21:19 -0800302 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800303 public static final String ACTION_TETHER_STATE_CHANGED =
304 "android.net.conn.TETHER_STATE_CHANGED";
305
306 /**
307 * @hide
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800308 * gives a String[] listing all the interfaces configured for
309 * tethering and currently available for tethering.
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800310 */
Robert Greenwalt2a091d72010-02-11 18:18:40 -0800311 public static final String EXTRA_AVAILABLE_TETHER = "availableArray";
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800312
313 /**
314 * @hide
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800315 * gives a String[] listing all the interfaces currently tethered
316 * (ie, has dhcp support and packets potentially forwarded/NATed)
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800317 */
Robert Greenwalt2a091d72010-02-11 18:18:40 -0800318 public static final String EXTRA_ACTIVE_TETHER = "activeArray";
319
320 /**
321 * @hide
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800322 * gives a String[] listing all the interfaces we tried to tether and
323 * failed. Use {@link #getLastTetherError} to find the error code
324 * for any interfaces listed here.
Robert Greenwalt2a091d72010-02-11 18:18:40 -0800325 */
326 public static final String EXTRA_ERRORED_TETHER = "erroredArray";
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800327
328 /**
Russell Brenner108da0c2013-02-12 10:03:14 -0800329 * Broadcast Action: The captive portal tracker has finished its test.
330 * Sent only while running Setup Wizard, in lieu of showing a user
331 * notification.
332 * @hide
333 */
Jeff Sharkey4fa63b22013-02-20 18:21:19 -0800334 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Russell Brenner108da0c2013-02-12 10:03:14 -0800335 public static final String ACTION_CAPTIVE_PORTAL_TEST_COMPLETED =
336 "android.net.conn.CAPTIVE_PORTAL_TEST_COMPLETED";
337 /**
338 * The lookup key for a boolean that indicates whether a captive portal was detected.
339 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
340 * @hide
341 */
342 public static final String EXTRA_IS_CAPTIVE_PORTAL = "captivePortal";
343
344 /**
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900345 * Action used to display a dialog that asks the user whether to connect to a network that is
346 * not validated. This intent is used to start the dialog in settings via startActivity.
347 *
348 * @hide
349 */
350 public static final String ACTION_PROMPT_UNVALIDATED = "android.net.conn.PROMPT_UNVALIDATED";
351
352 /**
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800353 * Invalid tethering type.
354 * @see #startTethering(int, OnStartTetheringCallback, boolean)
355 * @hide
356 */
357 public static final int TETHERING_INVALID = -1;
358
359 /**
360 * Wifi tethering type.
361 * @see #startTethering(int, OnStartTetheringCallback, boolean)
362 * @hide
363 */
364 @SystemApi
365 public static final int TETHERING_WIFI = 0;
366
367 /**
368 * USB tethering type.
369 * @see #startTethering(int, OnStartTetheringCallback, boolean)
370 * @hide
371 */
372 @SystemApi
373 public static final int TETHERING_USB = 1;
374
375 /**
376 * Bluetooth tethering type.
377 * @see #startTethering(int, OnStartTetheringCallback, boolean)
378 * @hide
379 */
380 @SystemApi
381 public static final int TETHERING_BLUETOOTH = 2;
382
383 /**
384 * Extra used for communicating with the TetherService. Includes the type of tethering to
385 * enable if any.
386 * @hide
387 */
388 public static final String EXTRA_ADD_TETHER_TYPE = "extraAddTetherType";
389
390 /**
391 * Extra used for communicating with the TetherService. Includes the type of tethering for
392 * which to cancel provisioning.
393 * @hide
394 */
395 public static final String EXTRA_REM_TETHER_TYPE = "extraRemTetherType";
396
397 /**
398 * Extra used for communicating with the TetherService. True to schedule a recheck of tether
399 * provisioning.
400 * @hide
401 */
402 public static final String EXTRA_SET_ALARM = "extraSetAlarm";
403
404 /**
405 * Tells the TetherService to run a provision check now.
406 * @hide
407 */
408 public static final String EXTRA_RUN_PROVISION = "extraRunProvision";
409
410 /**
411 * Extra used for communicating with the TetherService. Contains the {@link ResultReceiver}
412 * which will receive provisioning results. Can be left empty.
413 * @hide
414 */
415 public static final String EXTRA_PROVISION_CALLBACK = "extraProvisionCallback";
416
417 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800418 * The absence of a connection type.
Robert Greenwaltccf83af12011-06-02 17:30:47 -0700419 * @hide
420 */
421 public static final int TYPE_NONE = -1;
422
423 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800424 * The Mobile data connection. When active, all data traffic
425 * will use this network type's interface by default
426 * (it has a default route)
Robert Greenwalt42acef32009-08-12 16:08:25 -0700427 */
428 public static final int TYPE_MOBILE = 0;
429 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800430 * The WIFI data connection. When active, all data traffic
431 * will use this network type's interface by default
432 * (it has a default route).
Robert Greenwalt42acef32009-08-12 16:08:25 -0700433 */
434 public static final int TYPE_WIFI = 1;
435 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800436 * An MMS-specific Mobile data connection. This network type may use the
437 * same network interface as {@link #TYPE_MOBILE} or it may use a different
438 * one. This is used by applications needing to talk to the carrier's
439 * Multimedia Messaging Service servers.
Lorenzo Colittie285b432015-04-23 15:32:42 +0900440 *
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +0900441 * @deprecated Applications should instead use
442 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colittie285b432015-04-23 15:32:42 +0900443 * provides the {@link NetworkCapabilities#NET_CAPABILITY_MMS} capability.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700444 */
445 public static final int TYPE_MOBILE_MMS = 2;
446 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800447 * A SUPL-specific Mobile data connection. This network type may use the
448 * same network interface as {@link #TYPE_MOBILE} or it may use a different
449 * one. This is used by applications needing to talk to the carrier's
450 * Secure User Plane Location servers for help locating the device.
Lorenzo Colittie285b432015-04-23 15:32:42 +0900451 *
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +0900452 * @deprecated Applications should instead use
453 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colittie285b432015-04-23 15:32:42 +0900454 * provides the {@link NetworkCapabilities#NET_CAPABILITY_SUPL} capability.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700455 */
456 public static final int TYPE_MOBILE_SUPL = 3;
457 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800458 * A DUN-specific Mobile data connection. This network type may use the
459 * same network interface as {@link #TYPE_MOBILE} or it may use a different
460 * one. This is sometimes by the system when setting up an upstream connection
461 * for tethering so that the carrier is aware of DUN traffic.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700462 */
463 public static final int TYPE_MOBILE_DUN = 4;
464 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800465 * A High Priority Mobile data connection. This network type uses the
466 * same network interface as {@link #TYPE_MOBILE} but the routing setup
Lorenzo Colittie285b432015-04-23 15:32:42 +0900467 * is different.
468 *
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +0900469 * @deprecated Applications should instead use
470 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colittie285b432015-04-23 15:32:42 +0900471 * uses the {@link NetworkCapabilities#TRANSPORT_CELLULAR} transport.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700472 */
473 public static final int TYPE_MOBILE_HIPRI = 5;
jsh8214deb2010-03-11 15:04:43 -0800474 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800475 * The WiMAX data connection. When active, all data traffic
476 * will use this network type's interface by default
477 * (it has a default route).
jsh8214deb2010-03-11 15:04:43 -0800478 */
479 public static final int TYPE_WIMAX = 6;
Robert Greenwaltda3d5e62010-12-06 13:56:24 -0800480
Jaikumar Ganesh15c74392010-12-21 22:31:44 -0800481 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800482 * The Bluetooth data connection. When active, all data traffic
483 * will use this network type's interface by default
484 * (it has a default route).
Jaikumar Ganesh15c74392010-12-21 22:31:44 -0800485 */
486 public static final int TYPE_BLUETOOTH = 7;
487
Robert Greenwalt60810842011-04-22 15:28:18 -0700488 /**
489 * Dummy data connection. This should not be used on shipping devices.
490 */
Jaikumar Ganesh15c74392010-12-21 22:31:44 -0800491 public static final int TYPE_DUMMY = 8;
Wink Saville9d7d6282011-03-12 14:52:01 -0800492
Robert Greenwalt60810842011-04-22 15:28:18 -0700493 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800494 * The Ethernet data connection. When active, all data traffic
495 * will use this network type's interface by default
496 * (it has a default route).
Robert Greenwalt60810842011-04-22 15:28:18 -0700497 */
Robert Greenwalte12aec92011-01-28 14:48:37 -0800498 public static final int TYPE_ETHERNET = 9;
Robert Greenwalt60810842011-04-22 15:28:18 -0700499
Wink Saville9d7d6282011-03-12 14:52:01 -0800500 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800501 * Over the air Administration.
Wink Saville9d7d6282011-03-12 14:52:01 -0800502 * {@hide}
503 */
504 public static final int TYPE_MOBILE_FOTA = 10;
505
506 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800507 * IP Multimedia Subsystem.
Wink Saville9d7d6282011-03-12 14:52:01 -0800508 * {@hide}
509 */
510 public static final int TYPE_MOBILE_IMS = 11;
511
512 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800513 * Carrier Branded Services.
Wink Saville9d7d6282011-03-12 14:52:01 -0800514 * {@hide}
515 */
516 public static final int TYPE_MOBILE_CBS = 12;
517
repo syncaea743a2011-07-29 23:55:49 -0700518 /**
519 * A Wi-Fi p2p connection. Only requesting processes will have access to
520 * the peers connected.
521 * {@hide}
522 */
523 public static final int TYPE_WIFI_P2P = 13;
Wink Saville9d7d6282011-03-12 14:52:01 -0800524
Wink Saville5e56bc52013-07-29 15:00:57 -0700525 /**
526 * The network to use for initially attaching to the network
527 * {@hide}
528 */
529 public static final int TYPE_MOBILE_IA = 14;
repo syncaea743a2011-07-29 23:55:49 -0700530
Lorenzo Colittie285b432015-04-23 15:32:42 +0900531 /**
Robert Greenwalt4bd43892015-07-09 14:49:35 -0700532 * Emergency PDN connection for emergency services. This
533 * may include IMS and MMS in emergency situations.
Ram3e0e3bc2014-06-26 11:03:44 -0700534 * {@hide}
535 */
536 public static final int TYPE_MOBILE_EMERGENCY = 15;
537
Hui Lu1c5624a2014-01-15 11:05:36 -0500538 /**
539 * The network that uses proxy to achieve connectivity.
540 * {@hide}
541 */
542 public static final int TYPE_PROXY = 16;
Wink Saville5e56bc52013-07-29 15:00:57 -0700543
Robert Greenwalt8283f882014-07-07 17:09:01 -0700544 /**
545 * A virtual network using one or more native bearers.
546 * It may or may not be providing security services.
547 */
548 public static final int TYPE_VPN = 17;
Hui Lu1c5624a2014-01-15 11:05:36 -0500549
550 /** {@hide} */
Robert Greenwalt8283f882014-07-07 17:09:01 -0700551 public static final int MAX_RADIO_TYPE = TYPE_VPN;
552
553 /** {@hide} */
554 public static final int MAX_NETWORK_TYPE = TYPE_VPN;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800555
Jianzheng Zhoudcf03f32012-11-16 13:45:20 +0800556 /**
557 * If you want to set the default network preference,you can directly
558 * change the networkAttributes array in framework's config.xml.
559 *
560 * @deprecated Since we support so many more networks now, the single
561 * network default network preference can't really express
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800562 * the hierarchy. Instead, the default is defined by the
Jianzheng Zhoudcf03f32012-11-16 13:45:20 +0800563 * networkAttributes in config.xml. You can determine
Robert Greenwalt4c8b7482012-12-07 09:56:50 -0800564 * the current value by calling {@link #getNetworkPreference()}
Jianzheng Zhoudcf03f32012-11-16 13:45:20 +0800565 * from an App.
566 */
567 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800568 public static final int DEFAULT_NETWORK_PREFERENCE = TYPE_WIFI;
569
Jeff Sharkey625239a2012-09-26 22:03:49 -0700570 /**
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700571 * @hide
572 */
Robert Greenwalt7569f182014-06-08 16:42:59 -0700573 public final static int REQUEST_ID_UNSET = 0;
574
Paul Jensen5d59e782014-07-11 12:28:19 -0400575 /**
576 * A NetID indicating no Network is selected.
577 * Keep in sync with bionic/libc/dns/include/resolv_netid.h
578 * @hide
579 */
580 public static final int NETID_UNSET = 0;
581
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700582 private final IConnectivityManager mService;
Paul Jensene0bef712014-12-10 15:12:18 -0500583 /**
584 * A kludge to facilitate static access where a Context pointer isn't available, like in the
585 * case of the static set/getProcessDefaultNetwork methods and from the Network class.
586 * TODO: Remove this after deprecating the static methods in favor of non-static methods or
587 * methods that take a Context argument.
588 */
589 private static ConnectivityManager sInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800590
Lorenzo Colittiffc42b02015-07-29 11:41:21 +0900591 private final Context mContext;
592
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800593 private INetworkManagementService mNMService;
Felipe Leme1b103232016-01-22 09:44:57 -0800594 private INetworkPolicyManager mNPManager;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800595
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800596 /**
597 * Tests if a given integer represents a valid network type.
598 * @param networkType the type to be tested
599 * @return a boolean. {@code true} if the type is valid, else {@code false}
Paul Jensen9e59e122015-05-06 10:42:25 -0400600 * @deprecated All APIs accepting a network type are deprecated. There should be no need to
601 * validate a network type.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800602 */
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700603 public static boolean isNetworkTypeValid(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700604 return networkType >= 0 && networkType <= MAX_NETWORK_TYPE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800605 }
606
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800607 /**
608 * Returns a non-localized string representing a given network type.
609 * ONLY used for debugging output.
610 * @param type the type needing naming
611 * @return a String for the given type, or a string version of the type ("87")
612 * if no name is known.
613 * {@hide}
614 */
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700615 public static String getNetworkTypeName(int type) {
616 switch (type) {
617 case TYPE_MOBILE:
618 return "MOBILE";
619 case TYPE_WIFI:
620 return "WIFI";
621 case TYPE_MOBILE_MMS:
622 return "MOBILE_MMS";
623 case TYPE_MOBILE_SUPL:
624 return "MOBILE_SUPL";
625 case TYPE_MOBILE_DUN:
626 return "MOBILE_DUN";
627 case TYPE_MOBILE_HIPRI:
628 return "MOBILE_HIPRI";
629 case TYPE_WIMAX:
630 return "WIMAX";
631 case TYPE_BLUETOOTH:
632 return "BLUETOOTH";
633 case TYPE_DUMMY:
634 return "DUMMY";
635 case TYPE_ETHERNET:
636 return "ETHERNET";
637 case TYPE_MOBILE_FOTA:
638 return "MOBILE_FOTA";
639 case TYPE_MOBILE_IMS:
640 return "MOBILE_IMS";
641 case TYPE_MOBILE_CBS:
642 return "MOBILE_CBS";
repo syncaea743a2011-07-29 23:55:49 -0700643 case TYPE_WIFI_P2P:
644 return "WIFI_P2P";
Wink Saville5e56bc52013-07-29 15:00:57 -0700645 case TYPE_MOBILE_IA:
646 return "MOBILE_IA";
Ram3e0e3bc2014-06-26 11:03:44 -0700647 case TYPE_MOBILE_EMERGENCY:
648 return "MOBILE_EMERGENCY";
Hui Lu1c5624a2014-01-15 11:05:36 -0500649 case TYPE_PROXY:
650 return "PROXY";
Erik Kline37fbfa12014-11-19 17:23:41 +0900651 case TYPE_VPN:
652 return "VPN";
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700653 default:
654 return Integer.toString(type);
655 }
656 }
657
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800658 /**
659 * Checks if a given type uses the cellular data connection.
660 * This should be replaced in the future by a network property.
661 * @param networkType the type to check
662 * @return a boolean - {@code true} if uses cellular network, else {@code false}
663 * {@hide}
664 */
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700665 public static boolean isNetworkTypeMobile(int networkType) {
666 switch (networkType) {
667 case TYPE_MOBILE:
668 case TYPE_MOBILE_MMS:
669 case TYPE_MOBILE_SUPL:
670 case TYPE_MOBILE_DUN:
671 case TYPE_MOBILE_HIPRI:
672 case TYPE_MOBILE_FOTA:
673 case TYPE_MOBILE_IMS:
674 case TYPE_MOBILE_CBS:
Wink Saville5e56bc52013-07-29 15:00:57 -0700675 case TYPE_MOBILE_IA:
Ram3e0e3bc2014-06-26 11:03:44 -0700676 case TYPE_MOBILE_EMERGENCY:
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700677 return true;
678 default:
679 return false;
680 }
681 }
682
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800683 /**
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700684 * Checks if the given network type is backed by a Wi-Fi radio.
685 *
686 * @hide
687 */
688 public static boolean isNetworkTypeWifi(int networkType) {
689 switch (networkType) {
690 case TYPE_WIFI:
691 case TYPE_WIFI_P2P:
692 return true;
693 default:
694 return false;
695 }
696 }
697
698 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800699 * Specifies the preferred network type. When the device has more
700 * than one type available the preferred network type will be used.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800701 *
702 * @param preference the network type to prefer over all others. It is
703 * unspecified what happens to the old preferred network in the
704 * overall ordering.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -0700705 * @deprecated Functionality has been removed as it no longer makes sense,
706 * with many more than two networks - we'd need an array to express
707 * preference. Instead we use dynamic network properties of
708 * the networks to describe their precedence.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800709 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800710 public void setNetworkPreference(int preference) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800711 }
712
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800713 /**
714 * Retrieves the current preferred network type.
Paul Jensenb2748922015-05-06 11:10:18 -0400715 * <p>This method requires the caller to hold the permission
716 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800717 *
718 * @return an integer representing the preferred network type
719 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -0700720 * @deprecated Functionality has been removed as it no longer makes sense,
721 * with many more than two networks - we'd need an array to express
722 * preference. Instead we use dynamic network properties of
723 * the networks to describe their precedence.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800724 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800725 public int getNetworkPreference() {
Robert Greenwaltd19c41c2014-05-18 23:07:25 -0700726 return TYPE_NONE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800727 }
728
Scott Main671644c2011-10-06 19:02:28 -0700729 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800730 * Returns details about the currently active default data network. When
731 * connected, this network is the default route for outgoing connections.
732 * You should always check {@link NetworkInfo#isConnected()} before initiating
733 * network traffic. This may return {@code null} when there is no default
734 * network.
Paul Jensenb2748922015-05-06 11:10:18 -0400735 * <p>This method requires the caller to hold the permission
736 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800737 *
738 * @return a {@link NetworkInfo} object for the current default network
Paul Jensen0d719ca2015-02-13 14:18:39 -0500739 * or {@code null} if no default network is currently active
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -0700740 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800741 public NetworkInfo getActiveNetworkInfo() {
742 try {
743 return mService.getActiveNetworkInfo();
744 } catch (RemoteException e) {
745 return null;
746 }
747 }
748
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800749 /**
Paul Jensen31a94f42015-02-13 14:18:39 -0500750 * Returns a {@link Network} object corresponding to the currently active
751 * default data network. In the event that the current active default data
752 * network disconnects, the returned {@code Network} object will no longer
753 * be usable. This will return {@code null} when there is no default
754 * network.
Paul Jensenb2748922015-05-06 11:10:18 -0400755 * <p>This method requires the caller to hold the permission
756 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Paul Jensen31a94f42015-02-13 14:18:39 -0500757 *
758 * @return a {@link Network} object for the current default network or
759 * {@code null} if no default network is currently active
Paul Jensen31a94f42015-02-13 14:18:39 -0500760 */
761 public Network getActiveNetwork() {
762 try {
763 return mService.getActiveNetwork();
764 } catch (RemoteException e) {
765 return null;
766 }
767 }
768
769 /**
Robin Lee244ce8e2016-01-05 18:03:46 +0000770 * Configures an always-on VPN connection through a specific application.
771 * This connection is automatically granted and persisted after a reboot.
772 *
773 * <p>The designated package should declare a {@link VpnService} in its
774 * manifest guarded by {@link android.Manifest.permission.BIND_VPN_SERVICE},
775 * otherwise the call will fail.
776 *
777 * @param userId The identifier of the user to set an always-on VPN for.
778 * @param vpnPackage The package name for an installed VPN app on the device, or {@code null}
779 * to remove an existing always-on VPN configuration.
780
781 * @return {@code true} if the package is set as always-on VPN controller;
782 * {@code false} otherwise.
783 * @hide
784 */
785 public boolean setAlwaysOnVpnPackageForUser(int userId, @Nullable String vpnPackage) {
786 try {
787 return mService.setAlwaysOnVpnPackage(userId, vpnPackage);
788 } catch (RemoteException e) {
789 return false;
790 }
791 }
792
793 /**
794 * Returns the package name of the currently set always-on VPN application.
795 * If there is no always-on VPN set, or the VPN is provided by the system instead
796 * of by an app, {@code null} will be returned.
797 *
798 * @return Package name of VPN controller responsible for always-on VPN,
799 * or {@code null} if none is set.
800 * @hide
801 */
802 public String getAlwaysOnVpnPackageForUser(int userId) {
803 try {
804 return mService.getAlwaysOnVpnPackage(userId);
805 } catch (RemoteException e) {
806 return null;
807 }
808 }
809
810 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800811 * Returns details about the currently active default data network
812 * for a given uid. This is for internal use only to avoid spying
813 * other apps.
Paul Jensenb2748922015-05-06 11:10:18 -0400814 * <p>This method requires the caller to hold the permission
815 * {@link android.Manifest.permission#CONNECTIVITY_INTERNAL}
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800816 *
817 * @return a {@link NetworkInfo} object for the current default network
818 * for the given uid or {@code null} if no default network is
819 * available for the specified uid.
820 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800821 * {@hide}
822 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700823 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
824 try {
825 return mService.getActiveNetworkInfoForUid(uid);
826 } catch (RemoteException e) {
827 return null;
828 }
829 }
830
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800831 /**
832 * Returns connection status information about a particular
833 * network type.
Paul Jensenb2748922015-05-06 11:10:18 -0400834 * <p>This method requires the caller to hold the permission
835 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800836 *
837 * @param networkType integer specifying which networkType in
838 * which you're interested.
839 * @return a {@link NetworkInfo} object for the requested
840 * network type or {@code null} if the type is not
841 * supported by the device.
842 *
Paul Jensen3541e9f2015-03-18 12:23:02 -0400843 * @deprecated This method does not support multiple connected networks
844 * of the same type. Use {@link #getAllNetworks} and
845 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800846 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800847 public NetworkInfo getNetworkInfo(int networkType) {
848 try {
849 return mService.getNetworkInfo(networkType);
850 } catch (RemoteException e) {
851 return null;
852 }
853 }
854
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800855 /**
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -0700856 * Returns connection status information about a particular
857 * Network.
Paul Jensenb2748922015-05-06 11:10:18 -0400858 * <p>This method requires the caller to hold the permission
859 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -0700860 *
861 * @param network {@link Network} specifying which network
862 * in which you're interested.
863 * @return a {@link NetworkInfo} object for the requested
864 * network or {@code null} if the {@code Network}
865 * is not valid.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -0700866 */
867 public NetworkInfo getNetworkInfo(Network network) {
868 try {
869 return mService.getNetworkInfoForNetwork(network);
870 } catch (RemoteException e) {
871 return null;
872 }
873 }
874
875 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800876 * Returns connection status information about all network
877 * types supported by the device.
Paul Jensenb2748922015-05-06 11:10:18 -0400878 * <p>This method requires the caller to hold the permission
879 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800880 *
881 * @return an array of {@link NetworkInfo} objects. Check each
882 * {@link NetworkInfo#getType} for which type each applies.
883 *
Paul Jensen3541e9f2015-03-18 12:23:02 -0400884 * @deprecated This method does not support multiple connected networks
885 * of the same type. Use {@link #getAllNetworks} and
886 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800887 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800888 public NetworkInfo[] getAllNetworkInfo() {
889 try {
890 return mService.getAllNetworkInfo();
891 } catch (RemoteException e) {
892 return null;
893 }
894 }
895
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800896 /**
Lorenzo Colittib57edc52014-08-22 17:10:50 -0700897 * Returns the {@link Network} object currently serving a given type, or
898 * null if the given type is not connected.
899 *
900 * <p>This method requires the caller to hold the permission
901 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
902 *
903 * @hide
Paul Jensen3541e9f2015-03-18 12:23:02 -0400904 * @deprecated This method does not support multiple connected networks
905 * of the same type. Use {@link #getAllNetworks} and
906 * {@link #getNetworkInfo(android.net.Network)} instead.
Lorenzo Colittib57edc52014-08-22 17:10:50 -0700907 */
908 public Network getNetworkForType(int networkType) {
909 try {
910 return mService.getNetworkForType(networkType);
911 } catch (RemoteException e) {
912 return null;
913 }
914 }
915
916 /**
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -0700917 * Returns an array of all {@link Network} currently tracked by the
918 * framework.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -0700919 * <p>This method requires the caller to hold the permission
920 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Paul Jensenb2748922015-05-06 11:10:18 -0400921 *
922 * @return an array of {@link Network} objects.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -0700923 */
924 public Network[] getAllNetworks() {
925 try {
926 return mService.getAllNetworks();
927 } catch (RemoteException e) {
928 return null;
929 }
930 }
931
932 /**
Lorenzo Colittie285b432015-04-23 15:32:42 +0900933 * Returns an array of {@link android.net.NetworkCapabilities} objects, representing
Lorenzo Colitti403aa262014-11-28 11:21:30 +0900934 * the Networks that applications run by the given user will use by default.
935 * @hide
936 */
937 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
938 try {
939 return mService.getDefaultNetworkCapabilitiesForUser(userId);
940 } catch (RemoteException e) {
941 return null;
942 }
943 }
944
945 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800946 * Returns the IP information for the current default network.
Paul Jensenb2748922015-05-06 11:10:18 -0400947 * <p>This method requires the caller to hold the permission
948 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800949 *
950 * @return a {@link LinkProperties} object describing the IP info
951 * for the current default network, or {@code null} if there
952 * is no current default network.
953 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800954 * {@hide}
955 */
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700956 public LinkProperties getActiveLinkProperties() {
957 try {
958 return mService.getActiveLinkProperties();
959 } catch (RemoteException e) {
960 return null;
961 }
962 }
963
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800964 /**
965 * Returns the IP information for a given network type.
Paul Jensenb2748922015-05-06 11:10:18 -0400966 * <p>This method requires the caller to hold the permission
967 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800968 *
969 * @param networkType the network type of interest.
970 * @return a {@link LinkProperties} object describing the IP info
971 * for the given networkType, or {@code null} if there is
972 * no current default network.
973 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800974 * {@hide}
Paul Jensen3541e9f2015-03-18 12:23:02 -0400975 * @deprecated This method does not support multiple connected networks
976 * of the same type. Use {@link #getAllNetworks},
977 * {@link #getNetworkInfo(android.net.Network)}, and
978 * {@link #getLinkProperties(android.net.Network)} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800979 */
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700980 public LinkProperties getLinkProperties(int networkType) {
981 try {
Robert Greenwalt9258c642014-03-26 16:47:06 -0700982 return mService.getLinkPropertiesForType(networkType);
983 } catch (RemoteException e) {
984 return null;
985 }
986 }
987
Robert Greenwaltd19c41c2014-05-18 23:07:25 -0700988 /**
989 * Get the {@link LinkProperties} for the given {@link Network}. This
990 * will return {@code null} if the network is unknown.
Paul Jensenb2748922015-05-06 11:10:18 -0400991 * <p>This method requires the caller to hold the permission
992 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -0700993 *
994 * @param network The {@link Network} object identifying the network in question.
995 * @return The {@link LinkProperties} for the network, or {@code null}.
Paul Jensenb2748922015-05-06 11:10:18 -0400996 */
Robert Greenwalt9258c642014-03-26 16:47:06 -0700997 public LinkProperties getLinkProperties(Network network) {
998 try {
999 return mService.getLinkProperties(network);
1000 } catch (RemoteException e) {
1001 return null;
1002 }
1003 }
1004
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001005 /**
Lorenzo Colittie285b432015-04-23 15:32:42 +09001006 * Get the {@link android.net.NetworkCapabilities} for the given {@link Network}. This
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001007 * will return {@code null} if the network is unknown.
Paul Jensenb2748922015-05-06 11:10:18 -04001008 * <p>This method requires the caller to hold the permission
1009 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001010 *
1011 * @param network The {@link Network} object identifying the network in question.
Lorenzo Colittie285b432015-04-23 15:32:42 +09001012 * @return The {@link android.net.NetworkCapabilities} for the network, or {@code null}.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001013 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07001014 public NetworkCapabilities getNetworkCapabilities(Network network) {
1015 try {
1016 return mService.getNetworkCapabilities(network);
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001017 } catch (RemoteException e) {
1018 return null;
1019 }
1020 }
1021
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001022 /**
Udam Sainib7c24872016-01-04 12:16:14 -08001023 * Gets the URL that should be used for resolving whether a captive portal is present.
1024 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1025 * portal is present.
1026 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1027 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1028 *
1029 * @hide
1030 */
1031 @SystemApi
1032 public String getCaptivePortalServerUrl() {
1033 try {
1034 return mService.getCaptivePortalServerUrl();
1035 } catch (RemoteException e) {
1036 return null;
1037 }
1038 }
1039
1040 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001041 * Tells the underlying networking system that the caller wants to
1042 * begin using the named feature. The interpretation of {@code feature}
1043 * is completely up to each networking implementation.
Lorenzo Colittid5427052015-10-15 16:29:00 +09001044 *
1045 * <p>This method requires the caller to hold either the
1046 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1047 * or the ability to modify system settings as determined by
1048 * {@link android.provider.Settings.System#canWrite}.</p>
1049 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001050 * @param networkType specifies which network the request pertains to
1051 * @param feature the name of the feature to be used
1052 * @return an integer value representing the outcome of the request.
1053 * The interpretation of this value is specific to each networking
1054 * implementation+feature combination, except that the value {@code -1}
1055 * always indicates failure.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001056 *
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +09001057 * @deprecated Deprecated in favor of the cleaner
1058 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
Dianne Hackborn692a2442015-07-31 10:35:34 -07001059 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001060 * throw {@code UnsupportedOperationException} if called.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001061 */
1062 public int startUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001063 checkLegacyRoutingApiAccess();
Robert Greenwalt562cc542014-05-15 18:07:26 -07001064 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1065 if (netCap == null) {
1066 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1067 feature);
1068 return PhoneConstants.APN_REQUEST_FAILED;
1069 }
1070
1071 NetworkRequest request = null;
1072 synchronized (sLegacyRequests) {
1073 LegacyRequest l = sLegacyRequests.get(netCap);
1074 if (l != null) {
1075 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1076 renewRequestLocked(l);
1077 if (l.currentNetwork != null) {
1078 return PhoneConstants.APN_ALREADY_ACTIVE;
1079 } else {
1080 return PhoneConstants.APN_REQUEST_STARTED;
1081 }
1082 }
1083
1084 request = requestNetworkForFeatureLocked(netCap);
1085 }
1086 if (request != null) {
Robert Greenwalt257ee5f2014-06-20 10:58:45 -07001087 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001088 return PhoneConstants.APN_REQUEST_STARTED;
1089 } else {
1090 Log.d(TAG, " request Failed");
1091 return PhoneConstants.APN_REQUEST_FAILED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001092 }
1093 }
1094
1095 /**
1096 * Tells the underlying networking system that the caller is finished
1097 * using the named feature. The interpretation of {@code feature}
1098 * is completely up to each networking implementation.
Lorenzo Colittid5427052015-10-15 16:29:00 +09001099 *
1100 * <p>This method requires the caller to hold either the
1101 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1102 * or the ability to modify system settings as determined by
1103 * {@link android.provider.Settings.System#canWrite}.</p>
1104 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001105 * @param networkType specifies which network the request pertains to
1106 * @param feature the name of the feature that is no longer needed
1107 * @return an integer value representing the outcome of the request.
1108 * The interpretation of this value is specific to each networking
1109 * implementation+feature combination, except that the value {@code -1}
1110 * always indicates failure.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001111 *
Robert Greenwalta36c0742015-07-28 11:41:31 -07001112 * @deprecated Deprecated in favor of the cleaner {@link #unregisterNetworkCallback} API.
Dianne Hackborn692a2442015-07-31 10:35:34 -07001113 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001114 * throw {@code UnsupportedOperationException} if called.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001115 */
1116 public int stopUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001117 checkLegacyRoutingApiAccess();
Robert Greenwalt562cc542014-05-15 18:07:26 -07001118 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1119 if (netCap == null) {
1120 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
1121 feature);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001122 return -1;
1123 }
Robert Greenwalt562cc542014-05-15 18:07:26 -07001124
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001125 if (removeRequestForFeature(netCap)) {
Robert Greenwalt562cc542014-05-15 18:07:26 -07001126 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001127 }
1128 return 1;
1129 }
1130
1131 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
1132 if (networkType == TYPE_MOBILE) {
1133 int cap = -1;
1134 if ("enableMMS".equals(feature)) {
1135 cap = NetworkCapabilities.NET_CAPABILITY_MMS;
1136 } else if ("enableSUPL".equals(feature)) {
1137 cap = NetworkCapabilities.NET_CAPABILITY_SUPL;
1138 } else if ("enableDUN".equals(feature) || "enableDUNAlways".equals(feature)) {
1139 cap = NetworkCapabilities.NET_CAPABILITY_DUN;
1140 } else if ("enableHIPRI".equals(feature)) {
1141 cap = NetworkCapabilities.NET_CAPABILITY_INTERNET;
1142 } else if ("enableFOTA".equals(feature)) {
1143 cap = NetworkCapabilities.NET_CAPABILITY_FOTA;
1144 } else if ("enableIMS".equals(feature)) {
1145 cap = NetworkCapabilities.NET_CAPABILITY_IMS;
1146 } else if ("enableCBS".equals(feature)) {
1147 cap = NetworkCapabilities.NET_CAPABILITY_CBS;
1148 } else {
1149 return null;
1150 }
1151 NetworkCapabilities netCap = new NetworkCapabilities();
Robert Greenwalt7569f182014-06-08 16:42:59 -07001152 netCap.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR).addCapability(cap);
Paul Jensen487ffe72015-07-24 15:57:11 -04001153 netCap.maybeMarkCapabilitiesRestricted();
Robert Greenwalt562cc542014-05-15 18:07:26 -07001154 return netCap;
1155 } else if (networkType == TYPE_WIFI) {
1156 if ("p2p".equals(feature)) {
1157 NetworkCapabilities netCap = new NetworkCapabilities();
1158 netCap.addTransportType(NetworkCapabilities.TRANSPORT_WIFI);
Robert Greenwalt7569f182014-06-08 16:42:59 -07001159 netCap.addCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
Paul Jensen487ffe72015-07-24 15:57:11 -04001160 netCap.maybeMarkCapabilitiesRestricted();
Robert Greenwalt562cc542014-05-15 18:07:26 -07001161 return netCap;
1162 }
1163 }
1164 return null;
1165 }
1166
Robert Greenwalt06314e42014-10-29 14:04:06 -07001167 /**
1168 * Guess what the network request was trying to say so that the resulting
1169 * network is accessible via the legacy (deprecated) API such as
1170 * requestRouteToHost.
Lorenzo Colittidef4cb02015-11-25 20:28:50 +09001171 *
1172 * This means we should try to be fairly precise about transport and
Robert Greenwalt06314e42014-10-29 14:04:06 -07001173 * capability but ignore things such as networkSpecifier.
1174 * If the request has more than one transport or capability it doesn't
1175 * match the old legacy requests (they selected only single transport/capability)
1176 * so this function cannot map the request to a single legacy type and
1177 * the resulting network will not be available to the legacy APIs.
1178 *
Lorenzo Colittidef4cb02015-11-25 20:28:50 +09001179 * This code is only called from the requestNetwork API (L and above).
1180 *
1181 * Setting a legacy type causes CONNECTIVITY_ACTION broadcasts, which are expensive
1182 * because they wake up lots of apps - see http://b/23350688 . So we currently only
1183 * do this for SUPL requests, which are the only ones that we know need it. If
1184 * omitting these broadcasts causes unacceptable app breakage, then for backwards
1185 * compatibility we can send them:
1186 *
1187 * if (targetSdkVersion < Build.VERSION_CODES.M) && // legacy API unsupported >= M
1188 * targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP)) // requestNetwork not present < L
1189 *
Robert Greenwalt06314e42014-10-29 14:04:06 -07001190 * TODO - This should be removed when the legacy APIs are removed.
1191 */
Ye Wenb87875e2014-07-21 14:19:01 -07001192 private int inferLegacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
1193 if (netCap == null) {
1194 return TYPE_NONE;
1195 }
Robert Greenwalt06314e42014-10-29 14:04:06 -07001196
Ye Wenb87875e2014-07-21 14:19:01 -07001197 if (!netCap.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
1198 return TYPE_NONE;
1199 }
Robert Greenwalt06314e42014-10-29 14:04:06 -07001200
Lifu Tang30f95a72016-01-07 23:20:38 -08001201 // Do this only for SUPL, until GnssLocationProvider is fixed. http://b/25876485 .
Lorenzo Colittidef4cb02015-11-25 20:28:50 +09001202 if (!netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1203 // NOTE: if this causes app breakage, we should not just comment out this early return;
1204 // instead, we should make this early return conditional on the requesting app's target
1205 // SDK version, as described in the comment above.
1206 return TYPE_NONE;
1207 }
1208
Robert Greenwalt06314e42014-10-29 14:04:06 -07001209 String type = null;
1210 int result = TYPE_NONE;
1211
Ye Wenb87875e2014-07-21 14:19:01 -07001212 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
Robert Greenwalt06314e42014-10-29 14:04:06 -07001213 type = "enableCBS";
1214 result = TYPE_MOBILE_CBS;
1215 } else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1216 type = "enableIMS";
1217 result = TYPE_MOBILE_IMS;
1218 } else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1219 type = "enableFOTA";
1220 result = TYPE_MOBILE_FOTA;
1221 } else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1222 type = "enableDUN";
1223 result = TYPE_MOBILE_DUN;
1224 } else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
Lorenzo Colittidef4cb02015-11-25 20:28:50 +09001225 type = "enableSUPL";
Robert Greenwalt06314e42014-10-29 14:04:06 -07001226 result = TYPE_MOBILE_SUPL;
Robert Greenwalt74ab4fa2015-08-28 12:37:54 -07001227 // back out this hack for mms as they no longer need this and it's causing
1228 // device slowdowns - b/23350688 (note, supl still needs this)
1229 //} else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1230 // type = "enableMMS";
1231 // result = TYPE_MOBILE_MMS;
Robert Greenwalt06314e42014-10-29 14:04:06 -07001232 } else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1233 type = "enableHIPRI";
1234 result = TYPE_MOBILE_HIPRI;
Ye Wenb87875e2014-07-21 14:19:01 -07001235 }
Robert Greenwalt06314e42014-10-29 14:04:06 -07001236 if (type != null) {
1237 NetworkCapabilities testCap = networkCapabilitiesForFeature(TYPE_MOBILE, type);
1238 if (testCap.equalsNetCapabilities(netCap) && testCap.equalsTransportTypes(netCap)) {
1239 return result;
Ye Wenb87875e2014-07-21 14:19:01 -07001240 }
1241 }
1242 return TYPE_NONE;
1243 }
1244
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07001245 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
Robert Greenwalt562cc542014-05-15 18:07:26 -07001246 if (netCap == null) return TYPE_NONE;
1247 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
1248 return TYPE_MOBILE_CBS;
1249 }
1250 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1251 return TYPE_MOBILE_IMS;
1252 }
1253 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1254 return TYPE_MOBILE_FOTA;
1255 }
1256 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1257 return TYPE_MOBILE_DUN;
1258 }
1259 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1260 return TYPE_MOBILE_SUPL;
1261 }
1262 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1263 return TYPE_MOBILE_MMS;
1264 }
1265 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1266 return TYPE_MOBILE_HIPRI;
1267 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07001268 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
1269 return TYPE_WIFI_P2P;
1270 }
Robert Greenwalt562cc542014-05-15 18:07:26 -07001271 return TYPE_NONE;
1272 }
1273
1274 private static class LegacyRequest {
1275 NetworkCapabilities networkCapabilities;
1276 NetworkRequest networkRequest;
1277 int expireSequenceNumber;
1278 Network currentNetwork;
1279 int delay = -1;
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001280
1281 private void clearDnsBinding() {
1282 if (currentNetwork != null) {
1283 currentNetwork = null;
1284 setProcessDefaultNetworkForHostResolution(null);
1285 }
1286 }
1287
Robert Greenwalt6078b502014-06-11 16:05:07 -07001288 NetworkCallback networkCallback = new NetworkCallback() {
Robert Greenwalt562cc542014-05-15 18:07:26 -07001289 @Override
Robert Greenwalt6078b502014-06-11 16:05:07 -07001290 public void onAvailable(Network network) {
Robert Greenwalt562cc542014-05-15 18:07:26 -07001291 currentNetwork = network;
1292 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04001293 setProcessDefaultNetworkForHostResolution(network);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001294 }
1295 @Override
Robert Greenwalt6078b502014-06-11 16:05:07 -07001296 public void onLost(Network network) {
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001297 if (network.equals(currentNetwork)) clearDnsBinding();
Robert Greenwalt562cc542014-05-15 18:07:26 -07001298 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
1299 }
1300 };
1301 }
1302
Robert Greenwaltfab501672014-07-23 11:44:01 -07001303 private static HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
Robert Greenwalt562cc542014-05-15 18:07:26 -07001304 new HashMap<NetworkCapabilities, LegacyRequest>();
1305
1306 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
1307 synchronized (sLegacyRequests) {
1308 LegacyRequest l = sLegacyRequests.get(netCap);
1309 if (l != null) return l.networkRequest;
1310 }
1311 return null;
1312 }
1313
1314 private void renewRequestLocked(LegacyRequest l) {
1315 l.expireSequenceNumber++;
1316 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
1317 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
1318 }
1319
1320 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
1321 int ourSeqNum = -1;
1322 synchronized (sLegacyRequests) {
1323 LegacyRequest l = sLegacyRequests.get(netCap);
1324 if (l == null) return;
1325 ourSeqNum = l.expireSequenceNumber;
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001326 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001327 }
1328 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
1329 }
1330
1331 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
1332 int delay = -1;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07001333 int type = legacyTypeForNetworkCapabilities(netCap);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001334 try {
1335 delay = mService.getRestoreDefaultNetworkDelay(type);
1336 } catch (RemoteException e) {}
1337 LegacyRequest l = new LegacyRequest();
1338 l.networkCapabilities = netCap;
1339 l.delay = delay;
1340 l.expireSequenceNumber = 0;
Robert Greenwalt6078b502014-06-11 16:05:07 -07001341 l.networkRequest = sendRequestForNetwork(netCap, l.networkCallback, 0,
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07001342 REQUEST, type);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001343 if (l.networkRequest == null) return null;
1344 sLegacyRequests.put(netCap, l);
1345 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
1346 return l.networkRequest;
1347 }
1348
1349 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
1350 if (delay >= 0) {
1351 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
1352 Message msg = sCallbackHandler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
1353 sCallbackHandler.sendMessageDelayed(msg, delay);
1354 }
1355 }
1356
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001357 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
1358 final LegacyRequest l;
Robert Greenwalt562cc542014-05-15 18:07:26 -07001359 synchronized (sLegacyRequests) {
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001360 l = sLegacyRequests.remove(netCap);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001361 }
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001362 if (l == null) return false;
1363 unregisterNetworkCallback(l.networkCallback);
1364 l.clearDnsBinding();
1365 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001366 }
1367
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001368 /** @hide */
1369 public static class PacketKeepaliveCallback {
1370 /** The requested keepalive was successfully started. */
1371 public void onStarted() {}
1372 /** The keepalive was successfully stopped. */
1373 public void onStopped() {}
1374 /** An error occurred. */
1375 public void onError(int error) {}
1376 }
1377
1378 /**
1379 * Allows applications to request that the system periodically send specific packets on their
1380 * behalf, using hardware offload to save battery power.
1381 *
1382 * To request that the system send keepalives, call one of the methods that return a
1383 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
1384 * passing in a non-null callback. If the callback is successfully started, the callback's
1385 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
1386 * specifying one of the {@code ERROR_*} constants in this class.
1387 *
1388 * To stop an existing keepalive, call {@link stop}. The system will call {@code onStopped} if
1389 * the operation was successfull or {@code onError} if an error occurred.
1390 *
1391 * @hide
1392 */
1393 public class PacketKeepalive {
1394
1395 private static final String TAG = "PacketKeepalive";
1396
1397 /** @hide */
1398 public static final int SUCCESS = 0;
1399
1400 /** @hide */
1401 public static final int NO_KEEPALIVE = -1;
1402
1403 /** @hide */
1404 public static final int BINDER_DIED = -10;
1405
1406 /** The specified {@code Network} is not connected. */
1407 public static final int ERROR_INVALID_NETWORK = -20;
1408 /** The specified IP addresses are invalid. For example, the specified source IP address is
1409 * not configured on the specified {@code Network}. */
1410 public static final int ERROR_INVALID_IP_ADDRESS = -21;
1411 /** The requested port is invalid. */
1412 public static final int ERROR_INVALID_PORT = -22;
1413 /** The packet length is invalid (e.g., too long). */
1414 public static final int ERROR_INVALID_LENGTH = -23;
1415 /** The packet transmission interval is invalid (e.g., too short). */
1416 public static final int ERROR_INVALID_INTERVAL = -24;
1417
1418 /** The hardware does not support this request. */
1419 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
Lorenzo Colitti9d1284e2015-09-08 16:46:36 +09001420 /** The hardware returned an error. */
1421 public static final int ERROR_HARDWARE_ERROR = -31;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001422
1423 public static final int NATT_PORT = 4500;
1424
1425 private final Network mNetwork;
1426 private final PacketKeepaliveCallback mCallback;
1427 private final Looper mLooper;
1428 private final Messenger mMessenger;
1429
1430 private volatile Integer mSlot;
1431
1432 void stopLooper() {
1433 mLooper.quit();
1434 }
1435
1436 public void stop() {
1437 try {
1438 mService.stopKeepalive(mNetwork, mSlot);
1439 } catch (RemoteException e) {
1440 Log.e(TAG, "Error stopping packet keepalive: ", e);
1441 stopLooper();
1442 }
1443 }
1444
1445 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
1446 checkNotNull(network, "network cannot be null");
1447 checkNotNull(callback, "callback cannot be null");
1448 mNetwork = network;
1449 mCallback = callback;
1450 HandlerThread thread = new HandlerThread(TAG);
1451 thread.start();
1452 mLooper = thread.getLooper();
1453 mMessenger = new Messenger(new Handler(mLooper) {
1454 @Override
1455 public void handleMessage(Message message) {
1456 switch (message.what) {
1457 case NetworkAgent.EVENT_PACKET_KEEPALIVE:
1458 int error = message.arg2;
1459 try {
1460 if (error == SUCCESS) {
1461 if (mSlot == null) {
1462 mSlot = message.arg1;
1463 mCallback.onStarted();
1464 } else {
1465 mSlot = null;
1466 stopLooper();
1467 mCallback.onStopped();
1468 }
1469 } else {
1470 stopLooper();
1471 mCallback.onError(error);
1472 }
1473 } catch (Exception e) {
1474 Log.e(TAG, "Exception in keepalive callback(" + error + ")", e);
1475 }
1476 break;
1477 default:
1478 Log.e(TAG, "Unhandled message " + Integer.toHexString(message.what));
1479 break;
1480 }
1481 }
1482 });
1483 }
1484 }
1485
1486 /**
1487 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
1488 *
1489 * @hide
1490 */
1491 public PacketKeepalive startNattKeepalive(
1492 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
1493 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
1494 final PacketKeepalive k = new PacketKeepalive(network, callback);
1495 try {
1496 mService.startNattKeepalive(network, intervalSeconds, k.mMessenger, new Binder(),
1497 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
1498 } catch (RemoteException e) {
1499 Log.e(TAG, "Error starting packet keepalive: ", e);
1500 k.stopLooper();
1501 return null;
1502 }
1503 return k;
1504 }
1505
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001506 /**
1507 * Ensure that a network route exists to deliver traffic to the specified
1508 * host via the specified network interface. An attempt to add a route that
1509 * already exists is ignored, but treated as successful.
Lorenzo Colittid5427052015-10-15 16:29:00 +09001510 *
1511 * <p>This method requires the caller to hold either the
1512 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1513 * or the ability to modify system settings as determined by
1514 * {@link android.provider.Settings.System#canWrite}.</p>
1515 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001516 * @param networkType the type of the network over which traffic to the specified
1517 * host is to be routed
1518 * @param hostAddress the IP address of the host to which the route is desired
1519 * @return {@code true} on success, {@code false} on failure
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001520 *
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +09001521 * @deprecated Deprecated in favor of the
1522 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
1523 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
Dianne Hackborn692a2442015-07-31 10:35:34 -07001524 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001525 * throw {@code UnsupportedOperationException} if called.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001526 */
1527 public boolean requestRouteToHost(int networkType, int hostAddress) {
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001528 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001529 }
1530
1531 /**
1532 * Ensure that a network route exists to deliver traffic to the specified
1533 * host via the specified network interface. An attempt to add a route that
1534 * already exists is ignored, but treated as successful.
Lorenzo Colittid5427052015-10-15 16:29:00 +09001535 *
1536 * <p>This method requires the caller to hold either the
1537 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1538 * or the ability to modify system settings as determined by
1539 * {@link android.provider.Settings.System#canWrite}.</p>
1540 *
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001541 * @param networkType the type of the network over which traffic to the specified
1542 * host is to be routed
1543 * @param hostAddress the IP address of the host to which the route is desired
1544 * @return {@code true} on success, {@code false} on failure
1545 * @hide
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001546 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +09001547 * {@link #bindProcessToNetwork} API.
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001548 */
1549 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001550 checkLegacyRoutingApiAccess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001551 try {
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001552 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001553 } catch (RemoteException e) {
1554 return false;
1555 }
1556 }
1557
1558 /**
1559 * Returns the value of the setting for background data usage. If false,
1560 * applications should not use the network if the application is not in the
1561 * foreground. Developers should respect this setting, and check the value
1562 * of this before performing any background data operations.
1563 * <p>
1564 * All applications that have background services that use the network
1565 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001566 * <p>
Scott Main4cc53332011-10-06 18:32:43 -07001567 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001568 * background data depends on several combined factors, and this method will
1569 * always return {@code true}. Instead, when background data is unavailable,
1570 * {@link #getActiveNetworkInfo()} will now appear disconnected.
Danica Chang6fdd0c62010-08-11 14:54:43 -07001571 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001572 * @return Whether background data usage is allowed.
1573 */
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001574 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001575 public boolean getBackgroundDataSetting() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001576 // assume that background data is allowed; final authority is
1577 // NetworkInfo which may be blocked.
1578 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001579 }
1580
1581 /**
1582 * Sets the value of the setting for background data usage.
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001583 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001584 * @param allowBackgroundData Whether an application should use data while
1585 * it is in the background.
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001586 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001587 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
1588 * @see #getBackgroundDataSetting()
1589 * @hide
1590 */
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001591 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001592 public void setBackgroundDataSetting(boolean allowBackgroundData) {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001593 // ignored
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001594 }
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001595
1596 /**
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001597 * Return quota status for the current active network, or {@code null} if no
1598 * network is active. Quota status can change rapidly, so these values
1599 * shouldn't be cached.
Jeff Sharkey44a3e0d2011-10-06 10:50:09 -07001600 *
Paul Jensen0d719ca2015-02-13 14:18:39 -05001601 * <p>This method requires the caller to hold the permission
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001602 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
1603 *
Jeff Sharkey44a3e0d2011-10-06 10:50:09 -07001604 * @hide
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001605 */
1606 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1607 try {
1608 return mService.getActiveNetworkQuotaInfo();
1609 } catch (RemoteException e) {
1610 return null;
1611 }
1612 }
1613
1614 /**
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001615 * @hide
Robert Greenwaltafa05c02014-05-21 20:04:36 -07001616 * @deprecated Talk to TelephonyManager directly
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001617 */
1618 public boolean getMobileDataEnabled() {
Robert Greenwaltafa05c02014-05-21 20:04:36 -07001619 IBinder b = ServiceManager.getService(Context.TELEPHONY_SERVICE);
1620 if (b != null) {
1621 try {
1622 ITelephony it = ITelephony.Stub.asInterface(b);
Shishir Agrawal7ea3e8b2016-01-25 13:03:07 -08001623 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
Wink Saville36ffb042014-12-05 11:10:30 -08001624 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
1625 boolean retVal = it.getDataEnabled(subId);
1626 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
1627 + " retVal=" + retVal);
1628 return retVal;
Robert Greenwaltafa05c02014-05-21 20:04:36 -07001629 } catch (RemoteException e) { }
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001630 }
Wink Saville36ffb042014-12-05 11:10:30 -08001631 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
Robert Greenwaltafa05c02014-05-21 20:04:36 -07001632 return false;
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001633 }
1634
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001635 /**
Robert Greenwaltb2489872014-09-04 16:44:35 -07001636 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
Robert Greenwalt6078b502014-06-11 16:05:07 -07001637 * to find out when the system default network has gone in to a high power state.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001638 */
1639 public interface OnNetworkActiveListener {
1640 /**
1641 * Called on the main thread of the process to report that the current data network
1642 * has become active, and it is now a good time to perform any pending network
1643 * operations. Note that this listener only tells you when the network becomes
1644 * active; if at any other time you want to know whether it is active (and thus okay
1645 * to initiate network traffic), you can retrieve its instantaneous state with
Robert Greenwalt6078b502014-06-11 16:05:07 -07001646 * {@link ConnectivityManager#isDefaultNetworkActive}.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001647 */
1648 public void onNetworkActive();
1649 }
1650
1651 private INetworkManagementService getNetworkManagementService() {
1652 synchronized (this) {
1653 if (mNMService != null) {
1654 return mNMService;
1655 }
1656 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
1657 mNMService = INetworkManagementService.Stub.asInterface(b);
1658 return mNMService;
1659 }
1660 }
1661
1662 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
1663 mNetworkActivityListeners
1664 = new ArrayMap<OnNetworkActiveListener, INetworkActivityListener>();
1665
1666 /**
Robert Greenwalt6078b502014-06-11 16:05:07 -07001667 * Start listening to reports when the system's default data network is active, meaning it is
1668 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
1669 * to determine the current state of the system's default network after registering the
1670 * listener.
1671 * <p>
1672 * If the process default network has been set with
Paul Jensen72db88e2015-03-10 10:54:12 -04001673 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
Robert Greenwalt6078b502014-06-11 16:05:07 -07001674 * reflect the process's default, but the system default.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001675 *
1676 * @param l The listener to be told when the network is active.
1677 */
Robert Greenwaltb2489872014-09-04 16:44:35 -07001678 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001679 INetworkActivityListener rl = new INetworkActivityListener.Stub() {
1680 @Override
1681 public void onNetworkActive() throws RemoteException {
1682 l.onNetworkActive();
1683 }
1684 };
1685
1686 try {
1687 getNetworkManagementService().registerNetworkActivityListener(rl);
1688 mNetworkActivityListeners.put(l, rl);
1689 } catch (RemoteException e) {
1690 }
1691 }
1692
1693 /**
1694 * Remove network active listener previously registered with
Robert Greenwaltb2489872014-09-04 16:44:35 -07001695 * {@link #addDefaultNetworkActiveListener}.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001696 *
1697 * @param l Previously registered listener.
1698 */
Robert Greenwaltb2489872014-09-04 16:44:35 -07001699 public void removeDefaultNetworkActiveListener(OnNetworkActiveListener l) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001700 INetworkActivityListener rl = mNetworkActivityListeners.get(l);
1701 if (rl == null) {
1702 throw new IllegalArgumentException("Listener not registered: " + l);
1703 }
1704 try {
1705 getNetworkManagementService().unregisterNetworkActivityListener(rl);
1706 } catch (RemoteException e) {
1707 }
1708 }
1709
1710 /**
1711 * Return whether the data network is currently active. An active network means that
1712 * it is currently in a high power state for performing data transmission. On some
1713 * types of networks, it may be expensive to move and stay in such a state, so it is
1714 * more power efficient to batch network traffic together when the radio is already in
1715 * this state. This method tells you whether right now is currently a good time to
1716 * initiate network traffic, as the network is already active.
1717 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07001718 public boolean isDefaultNetworkActive() {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001719 try {
1720 return getNetworkManagementService().isNetworkActive();
1721 } catch (RemoteException e) {
1722 }
1723 return false;
1724 }
1725
1726 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001727 * {@hide}
1728 */
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001729 public ConnectivityManager(Context context, IConnectivityManager service) {
1730 mContext = checkNotNull(context, "missing context");
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001731 mService = checkNotNull(service, "missing IConnectivityManager");
Paul Jensene0bef712014-12-10 15:12:18 -05001732 sInstance = this;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001733 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001734
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001735 /** {@hide} */
1736 public static ConnectivityManager from(Context context) {
1737 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
1738 }
1739
Lorenzo Colittid5427052015-10-15 16:29:00 +09001740 /** {@hide} */
1741 public static final void enforceChangePermission(Context context) {
1742 int uid = Binder.getCallingUid();
1743 Settings.checkAndNoteChangeNetworkStateOperation(context, uid, Settings
1744 .getPackageNameForUid(context, uid), true /* throwException */);
1745 }
1746
Robert Greenwaltedb47662014-09-16 17:54:19 -07001747 /** {@hide */
1748 public static final void enforceTetherChangePermission(Context context) {
1749 if (context.getResources().getStringArray(
1750 com.android.internal.R.array.config_mobile_hotspot_provision_app).length == 2) {
1751 // Have a provisioning app - must only let system apps (which check this app)
1752 // turn on tethering
1753 context.enforceCallingOrSelfPermission(
Jeremy Kleind42209d2015-12-28 15:11:58 -08001754 android.Manifest.permission.TETHER_PRIVILEGED, "ConnectivityService");
Robert Greenwaltedb47662014-09-16 17:54:19 -07001755 } else {
Billy Laua7238a32015-08-01 12:45:02 +01001756 int uid = Binder.getCallingUid();
Lorenzo Colittid5427052015-10-15 16:29:00 +09001757 Settings.checkAndNoteWriteSettingsOperation(context, uid, Settings
1758 .getPackageNameForUid(context, uid), true /* throwException */);
Robert Greenwaltedb47662014-09-16 17:54:19 -07001759 }
1760 }
1761
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001762 /**
Paul Jensene0bef712014-12-10 15:12:18 -05001763 * @deprecated - use getSystemService. This is a kludge to support static access in certain
1764 * situations where a Context pointer is unavailable.
1765 * @hide
1766 */
Paul Jensen72db88e2015-03-10 10:54:12 -04001767 static ConnectivityManager getInstanceOrNull() {
1768 return sInstance;
1769 }
1770
1771 /**
1772 * @deprecated - use getSystemService. This is a kludge to support static access in certain
1773 * situations where a Context pointer is unavailable.
1774 * @hide
1775 */
1776 private static ConnectivityManager getInstance() {
1777 if (getInstanceOrNull() == null) {
Paul Jensene0bef712014-12-10 15:12:18 -05001778 throw new IllegalStateException("No ConnectivityManager yet constructed");
1779 }
Paul Jensen72db88e2015-03-10 10:54:12 -04001780 return getInstanceOrNull();
Paul Jensene0bef712014-12-10 15:12:18 -05001781 }
1782
1783 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001784 * Get the set of tetherable, available interfaces. This list is limited by
1785 * device configuration and current interface existence.
Paul Jensenb2748922015-05-06 11:10:18 -04001786 * <p>This method requires the caller to hold the permission
1787 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001788 *
1789 * @return an array of 0 or more Strings of tetherable interface names.
1790 *
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001791 * {@hide}
1792 */
1793 public String[] getTetherableIfaces() {
1794 try {
1795 return mService.getTetherableIfaces();
1796 } catch (RemoteException e) {
1797 return new String[0];
1798 }
1799 }
1800
1801 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001802 * Get the set of tethered interfaces.
Paul Jensenb2748922015-05-06 11:10:18 -04001803 * <p>This method requires the caller to hold the permission
1804 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001805 *
1806 * @return an array of 0 or more String of currently tethered interface names.
1807 *
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001808 * {@hide}
1809 */
1810 public String[] getTetheredIfaces() {
1811 try {
1812 return mService.getTetheredIfaces();
1813 } catch (RemoteException e) {
1814 return new String[0];
1815 }
1816 }
1817
1818 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001819 * Get the set of interface names which attempted to tether but
1820 * failed. Re-attempting to tether may cause them to reset to the Tethered
1821 * state. Alternatively, causing the interface to be destroyed and recreated
1822 * may cause them to reset to the available state.
1823 * {@link ConnectivityManager#getLastTetherError} can be used to get more
1824 * information on the cause of the errors.
Paul Jensenb2748922015-05-06 11:10:18 -04001825 * <p>This method requires the caller to hold the permission
1826 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001827 *
1828 * @return an array of 0 or more String indicating the interface names
1829 * which failed to tether.
1830 *
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001831 * {@hide}
1832 */
Robert Greenwalt5a735062010-03-02 17:25:02 -08001833 public String[] getTetheringErroredIfaces() {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001834 try {
Robert Greenwalt5a735062010-03-02 17:25:02 -08001835 return mService.getTetheringErroredIfaces();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001836 } catch (RemoteException e) {
Robert Greenwalt5a735062010-03-02 17:25:02 -08001837 return new String[0];
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001838 }
1839 }
1840
1841 /**
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07001842 * Get the set of tethered dhcp ranges.
1843 *
1844 * @return an array of 0 or more {@code String} of tethered dhcp ranges.
1845 * {@hide}
1846 */
1847 public String[] getTetheredDhcpRanges() {
1848 try {
1849 return mService.getTetheredDhcpRanges();
1850 } catch (RemoteException e) {
1851 return new String[0];
1852 }
1853 }
1854
1855 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001856 * Attempt to tether the named interface. This will setup a dhcp server
1857 * on the interface, forward and NAT IP packets and forward DNS requests
1858 * to the best active upstream network interface. Note that if no upstream
1859 * IP network interface is available, dhcp will still run and traffic will be
1860 * allowed between the tethered devices and this device, though upstream net
1861 * access will of course fail until an upstream network interface becomes
1862 * active.
Lorenzo Colittid5427052015-10-15 16:29:00 +09001863 *
1864 * <p>This method requires the caller to hold either the
1865 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1866 * or the ability to modify system settings as determined by
1867 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001868 *
Jeremy Klein36c7aa02016-01-22 14:11:45 -08001869 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
1870 * and WifiStateMachine which need direct access. All other clients should use
1871 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
1872 * logic.</p>
1873 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001874 * @param iface the interface name to tether.
1875 * @return error a {@code TETHER_ERROR} value indicating success or failure type
1876 *
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001877 * {@hide}
1878 */
Robert Greenwalt5a735062010-03-02 17:25:02 -08001879 public int tether(String iface) {
1880 try {
1881 return mService.tether(iface);
1882 } catch (RemoteException e) {
1883 return TETHER_ERROR_SERVICE_UNAVAIL;
1884 }
1885 }
1886
1887 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001888 * Stop tethering the named interface.
Lorenzo Colittid5427052015-10-15 16:29:00 +09001889 *
1890 * <p>This method requires the caller to hold either the
1891 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1892 * or the ability to modify system settings as determined by
1893 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001894 *
Jeremy Klein36c7aa02016-01-22 14:11:45 -08001895 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
1896 * and WifiStateMachine which need direct access. All other clients should use
1897 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
1898 * logic.</p>
1899 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001900 * @param iface the interface name to untether.
1901 * @return error a {@code TETHER_ERROR} value indicating success or failure type
1902 *
Robert Greenwalt5a735062010-03-02 17:25:02 -08001903 * {@hide}
1904 */
1905 public int untether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001906 try {
1907 return mService.untether(iface);
1908 } catch (RemoteException e) {
Robert Greenwalt5a735062010-03-02 17:25:02 -08001909 return TETHER_ERROR_SERVICE_UNAVAIL;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001910 }
1911 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001912
1913 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001914 * Check if the device allows for tethering. It may be disabled via
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001915 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001916 * due to device configuration.
Paul Jensenb2748922015-05-06 11:10:18 -04001917 * <p>This method requires the caller to hold the permission
1918 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001919 *
1920 * @return a boolean - {@code true} indicating Tethering is supported.
1921 *
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001922 * {@hide}
1923 */
Jeremy Klein36c7aa02016-01-22 14:11:45 -08001924 @SystemApi
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001925 public boolean isTetheringSupported() {
1926 try {
1927 return mService.isTetheringSupported();
1928 } catch (RemoteException e) {
1929 return false;
1930 }
1931 }
1932
1933 /**
Jeremy Klein36c7aa02016-01-22 14:11:45 -08001934 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
1935 * @hide
1936 */
1937 @SystemApi
1938 public static abstract class OnStartTetheringCallback {
1939 /**
1940 * Called when tethering has been successfully started.
1941 */
1942 public void onTetheringStarted() {};
1943
1944 /**
1945 * Called when starting tethering failed.
1946 */
1947 public void onTetheringFailed() {};
1948 }
1949
1950 /**
1951 * Convenient overload for
1952 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
1953 * handler to run on the current thread's {@link Looper}.
1954 * @hide
1955 */
1956 @SystemApi
1957 public void startTethering(int type, boolean showProvisioningUi,
1958 final OnStartTetheringCallback callback) {
1959 startTethering(type, showProvisioningUi, callback, null);
1960 }
1961
1962 /**
1963 * Runs tether provisioning for the given type if needed and then starts tethering if
1964 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
1965 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
1966 * schedules tether provisioning re-checks if appropriate.
1967 *
1968 * @param type The type of tethering to start. Must be one of
1969 * {@link ConnectivityManager.TETHERING_WIFI},
1970 * {@link ConnectivityManager.TETHERING_USB}, or
1971 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
1972 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
1973 * is one. This should be true the first time this function is called and also any time
1974 * the user can see this UI. It gives users information from their carrier about the
1975 * check failing and how they can sign up for tethering if possible.
1976 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
1977 * of the result of trying to tether.
1978 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
1979 * @hide
1980 */
1981 @SystemApi
1982 public void startTethering(int type, boolean showProvisioningUi,
1983 final OnStartTetheringCallback callback, Handler handler) {
1984 ResultReceiver wrappedCallback = new ResultReceiver(handler) {
1985 @Override
1986 protected void onReceiveResult(int resultCode, Bundle resultData) {
1987 if (resultCode == TETHER_ERROR_NO_ERROR) {
1988 callback.onTetheringStarted();
1989 } else {
1990 callback.onTetheringFailed();
1991 }
1992 }
1993 };
1994 try {
1995 mService.startTethering(type, wrappedCallback, showProvisioningUi);
1996 } catch (RemoteException e) {
1997 Log.e(TAG, "Exception trying to start tethering.", e);
1998 wrappedCallback.send(TETHER_ERROR_SERVICE_UNAVAIL, null);
1999 }
2000 }
2001
2002 /**
2003 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
2004 * applicable.
2005 *
2006 * @param type The type of tethering to stop. Must be one of
2007 * {@link ConnectivityManager.TETHERING_WIFI},
2008 * {@link ConnectivityManager.TETHERING_USB}, or
2009 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2010 * @hide
2011 */
2012 @SystemApi
2013 public void stopTethering(int type) {
2014 try {
2015 mService.stopTethering(type);
2016 } catch (RemoteException e) {
2017 Log.e(TAG, "Exception trying to stop tethering.", e);
2018 }
2019 }
2020
2021 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002022 * Get the list of regular expressions that define any tetherable
2023 * USB network interfaces. If USB tethering is not supported by the
2024 * device, this list should be empty.
Paul Jensenb2748922015-05-06 11:10:18 -04002025 * <p>This method requires the caller to hold the permission
2026 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002027 *
2028 * @return an array of 0 or more regular expression Strings defining
2029 * what interfaces are considered tetherable usb interfaces.
2030 *
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002031 * {@hide}
2032 */
2033 public String[] getTetherableUsbRegexs() {
2034 try {
2035 return mService.getTetherableUsbRegexs();
2036 } catch (RemoteException e) {
2037 return new String[0];
2038 }
2039 }
2040
2041 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002042 * Get the list of regular expressions that define any tetherable
2043 * Wifi network interfaces. If Wifi tethering is not supported by the
2044 * device, this list should be empty.
Paul Jensenb2748922015-05-06 11:10:18 -04002045 * <p>This method requires the caller to hold the permission
2046 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002047 *
2048 * @return an array of 0 or more regular expression Strings defining
2049 * what interfaces are considered tetherable wifi interfaces.
2050 *
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002051 * {@hide}
2052 */
2053 public String[] getTetherableWifiRegexs() {
2054 try {
2055 return mService.getTetherableWifiRegexs();
2056 } catch (RemoteException e) {
2057 return new String[0];
2058 }
2059 }
Robert Greenwalt5a735062010-03-02 17:25:02 -08002060
Danica Chang6fdd0c62010-08-11 14:54:43 -07002061 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002062 * Get the list of regular expressions that define any tetherable
2063 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
2064 * device, this list should be empty.
Paul Jensenb2748922015-05-06 11:10:18 -04002065 * <p>This method requires the caller to hold the permission
2066 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002067 *
2068 * @return an array of 0 or more regular expression Strings defining
2069 * what interfaces are considered tetherable bluetooth interfaces.
2070 *
Danica Chang6fdd0c62010-08-11 14:54:43 -07002071 * {@hide}
2072 */
2073 public String[] getTetherableBluetoothRegexs() {
2074 try {
2075 return mService.getTetherableBluetoothRegexs();
2076 } catch (RemoteException e) {
2077 return new String[0];
2078 }
2079 }
2080
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002081 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002082 * Attempt to both alter the mode of USB and Tethering of USB. A
2083 * utility method to deal with some of the complexity of USB - will
2084 * attempt to switch to Rndis and subsequently tether the resulting
2085 * interface on {@code true} or turn off tethering and switch off
2086 * Rndis on {@code false}.
Lorenzo Colittid5427052015-10-15 16:29:00 +09002087 *
2088 * <p>This method requires the caller to hold either the
2089 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2090 * or the ability to modify system settings as determined by
2091 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002092 *
2093 * @param enable a boolean - {@code true} to enable tethering
2094 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2095 *
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002096 * {@hide}
2097 */
2098 public int setUsbTethering(boolean enable) {
2099 try {
2100 return mService.setUsbTethering(enable);
2101 } catch (RemoteException e) {
2102 return TETHER_ERROR_SERVICE_UNAVAIL;
2103 }
2104 }
2105
Robert Greenwalt5a735062010-03-02 17:25:02 -08002106 /** {@hide} */
2107 public static final int TETHER_ERROR_NO_ERROR = 0;
2108 /** {@hide} */
2109 public static final int TETHER_ERROR_UNKNOWN_IFACE = 1;
2110 /** {@hide} */
2111 public static final int TETHER_ERROR_SERVICE_UNAVAIL = 2;
2112 /** {@hide} */
2113 public static final int TETHER_ERROR_UNSUPPORTED = 3;
2114 /** {@hide} */
2115 public static final int TETHER_ERROR_UNAVAIL_IFACE = 4;
2116 /** {@hide} */
2117 public static final int TETHER_ERROR_MASTER_ERROR = 5;
2118 /** {@hide} */
2119 public static final int TETHER_ERROR_TETHER_IFACE_ERROR = 6;
2120 /** {@hide} */
2121 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR = 7;
2122 /** {@hide} */
2123 public static final int TETHER_ERROR_ENABLE_NAT_ERROR = 8;
2124 /** {@hide} */
2125 public static final int TETHER_ERROR_DISABLE_NAT_ERROR = 9;
2126 /** {@hide} */
2127 public static final int TETHER_ERROR_IFACE_CFG_ERROR = 10;
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002128 /** {@hide} */
2129 public static final int TETHER_ERROR_PROVISION_FAILED = 11;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002130
2131 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002132 * Get a more detailed error code after a Tethering or Untethering
2133 * request asynchronously failed.
Paul Jensenb2748922015-05-06 11:10:18 -04002134 * <p>This method requires the caller to hold the permission
2135 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002136 *
2137 * @param iface The name of the interface of interest
Robert Greenwalt5a735062010-03-02 17:25:02 -08002138 * @return error The error code of the last error tethering or untethering the named
2139 * interface
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002140 *
Robert Greenwalt5a735062010-03-02 17:25:02 -08002141 * {@hide}
2142 */
2143 public int getLastTetherError(String iface) {
2144 try {
2145 return mService.getLastTetherError(iface);
2146 } catch (RemoteException e) {
2147 return TETHER_ERROR_SERVICE_UNAVAIL;
2148 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002149 }
2150
2151 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002152 * Report network connectivity status. This is currently used only
2153 * to alter status bar UI.
Paul Jensenb2748922015-05-06 11:10:18 -04002154 * <p>This method requires the caller to hold the permission
2155 * {@link android.Manifest.permission#STATUS_BAR}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002156 *
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002157 * @param networkType The type of network you want to report on
2158 * @param percentage The quality of the connection 0 is bad, 100 is good
2159 * {@hide}
2160 */
2161 public void reportInetCondition(int networkType, int percentage) {
2162 try {
2163 mService.reportInetCondition(networkType, percentage);
2164 } catch (RemoteException e) {
2165 }
2166 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002167
2168 /**
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002169 * Report a problem network to the framework. This provides a hint to the system
Ye Wenb87875e2014-07-21 14:19:01 -07002170 * that there might be connectivity problems on this network and may cause
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002171 * the framework to re-evaluate network connectivity and/or switch to another
2172 * network.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002173 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002174 * @param network The {@link Network} the application was attempting to use
2175 * or {@code null} to indicate the current default network.
Paul Jensenbfd17b72015-04-07 12:43:13 -04002176 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
2177 * working and non-working connectivity.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002178 */
2179 public void reportBadNetwork(Network network) {
2180 try {
Paul Jensenbfd17b72015-04-07 12:43:13 -04002181 // One of these will be ignored because it matches system's current state.
2182 // The other will trigger the necessary reevaluation.
2183 mService.reportNetworkConnectivity(network, true);
2184 mService.reportNetworkConnectivity(network, false);
2185 } catch (RemoteException e) {
2186 }
2187 }
2188
2189 /**
2190 * Report to the framework whether a network has working connectivity.
2191 * This provides a hint to the system that a particular network is providing
2192 * working connectivity or not. In response the framework may re-evaluate
2193 * the network's connectivity and might take further action thereafter.
2194 *
2195 * @param network The {@link Network} the application was attempting to use
2196 * or {@code null} to indicate the current default network.
2197 * @param hasConnectivity {@code true} if the application was able to successfully access the
2198 * Internet using {@code network} or {@code false} if not.
2199 */
2200 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
2201 try {
2202 mService.reportNetworkConnectivity(network, hasConnectivity);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002203 } catch (RemoteException e) {
2204 }
2205 }
2206
2207 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002208 * Set a network-independent global http proxy. This is not normally what you want
2209 * for typical HTTP proxies - they are general network dependent. However if you're
2210 * doing something unusual like general internal filtering this may be useful. On
2211 * a private network where the proxy is not accessible, you may break HTTP using this.
Paul Jensen0d719ca2015-02-13 14:18:39 -05002212 * <p>This method requires the caller to hold the permission
Jason Monkfaf3fd52014-05-07 18:41:13 -04002213 * android.Manifest.permission#CONNECTIVITY_INTERNAL.
Paul Jensenb2748922015-05-06 11:10:18 -04002214 *
2215 * @param p A {@link ProxyInfo} object defining the new global
2216 * HTTP proxy. A {@code null} value will clear the global HTTP proxy.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002217 * @hide
Robert Greenwalt434203a2010-10-11 16:00:27 -07002218 */
Jason Monk207900c2014-04-25 15:00:09 -04002219 public void setGlobalProxy(ProxyInfo p) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002220 try {
2221 mService.setGlobalProxy(p);
2222 } catch (RemoteException e) {
2223 }
2224 }
2225
2226 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002227 * Retrieve any network-independent global HTTP proxy.
2228 *
Jason Monk207900c2014-04-25 15:00:09 -04002229 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002230 * if no global HTTP proxy is set.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002231 * @hide
Robert Greenwalt434203a2010-10-11 16:00:27 -07002232 */
Jason Monk207900c2014-04-25 15:00:09 -04002233 public ProxyInfo getGlobalProxy() {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002234 try {
2235 return mService.getGlobalProxy();
2236 } catch (RemoteException e) {
2237 return null;
2238 }
2239 }
2240
2241 /**
Paul Jensencee9b512015-05-06 07:32:40 -04002242 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
2243 * network-specific HTTP proxy. If {@code network} is null, the
2244 * network-specific proxy returned is the proxy of the default active
2245 * network.
2246 *
2247 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
2248 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
2249 * or when {@code network} is {@code null},
2250 * the {@code ProxyInfo} for the default active network. Returns
2251 * {@code null} when no proxy applies or the caller doesn't have
2252 * permission to use {@code network}.
2253 * @hide
2254 */
2255 public ProxyInfo getProxyForNetwork(Network network) {
2256 try {
2257 return mService.getProxyForNetwork(network);
2258 } catch (RemoteException e) {
2259 return null;
2260 }
2261 }
2262
2263 /**
Paul Jensene0bef712014-12-10 15:12:18 -05002264 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
2265 * otherwise if this process is bound to a {@link Network} using
Paul Jensen72db88e2015-03-10 10:54:12 -04002266 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
Paul Jensene0bef712014-12-10 15:12:18 -05002267 * the default network's proxy is returned.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002268 *
Jason Monk207900c2014-04-25 15:00:09 -04002269 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002270 * HTTP proxy is active.
Robert Greenwalt434203a2010-10-11 16:00:27 -07002271 */
Paul Jensene0bef712014-12-10 15:12:18 -05002272 public ProxyInfo getDefaultProxy() {
Paul Jensencee9b512015-05-06 07:32:40 -04002273 return getProxyForNetwork(getBoundNetworkForProcess());
Robert Greenwalt434203a2010-10-11 16:00:27 -07002274 }
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002275
2276 /**
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07002277 * Returns true if the hardware supports the given network type
2278 * else it returns false. This doesn't indicate we have coverage
2279 * or are authorized onto a network, just whether or not the
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002280 * hardware supports it. For example a GSM phone without a SIM
2281 * should still return {@code true} for mobile data, but a wifi only
2282 * tablet would return {@code false}.
Paul Jensenb2748922015-05-06 11:10:18 -04002283 * <p>This method requires the caller to hold the permission
2284 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002285 *
2286 * @param networkType The network type we'd like to check
2287 * @return {@code true} if supported, else {@code false}
2288 *
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07002289 * @hide
2290 */
2291 public boolean isNetworkSupported(int networkType) {
2292 try {
2293 return mService.isNetworkSupported(networkType);
2294 } catch (RemoteException e) {}
2295 return false;
2296 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002297
2298 /**
2299 * Returns if the currently active data network is metered. A network is
2300 * classified as metered when the user is sensitive to heavy data usage on
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002301 * that connection due to monetary costs, data limitations or
2302 * battery/performance issues. You should check this before doing large
2303 * data transfers, and warn the user or delay the operation until another
2304 * network is available.
Paul Jensenb2748922015-05-06 11:10:18 -04002305 * <p>This method requires the caller to hold the permission
2306 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002307 *
2308 * @return {@code true} if large transfers should be avoided, otherwise
2309 * {@code false}.
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002310 */
2311 public boolean isActiveNetworkMetered() {
2312 try {
2313 return mService.isActiveNetworkMetered();
2314 } catch (RemoteException e) {
2315 return false;
2316 }
2317 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002318
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002319 /**
2320 * If the LockdownVpn mechanism is enabled, updates the vpn
2321 * with a reload of its profile.
2322 *
2323 * @return a boolean with {@code} indicating success
2324 *
2325 * <p>This method can only be called by the system UID
2326 * {@hide}
2327 */
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002328 public boolean updateLockdownVpn() {
2329 try {
2330 return mService.updateLockdownVpn();
2331 } catch (RemoteException e) {
2332 return false;
2333 }
2334 }
Irfan Sheriffda6da092012-08-16 12:49:23 -07002335
2336 /**
Wink Saville948282b2013-08-29 08:55:16 -07002337 * Check mobile provisioning.
Wink Savilleab9321d2013-06-29 21:10:57 -07002338 *
Wink Savilleab9321d2013-06-29 21:10:57 -07002339 * @param suggestedTimeOutMs, timeout in milliseconds
Wink Savilleab9321d2013-06-29 21:10:57 -07002340 *
2341 * @return time out that will be used, maybe less that suggestedTimeOutMs
2342 * -1 if an error.
2343 *
2344 * {@hide}
2345 */
Wink Saville948282b2013-08-29 08:55:16 -07002346 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Wink Savilleab9321d2013-06-29 21:10:57 -07002347 int timeOutMs = -1;
2348 try {
Wink Saville948282b2013-08-29 08:55:16 -07002349 timeOutMs = mService.checkMobileProvisioning(suggestedTimeOutMs);
Wink Savilleab9321d2013-06-29 21:10:57 -07002350 } catch (RemoteException e) {
2351 }
2352 return timeOutMs;
2353 }
Robert Greenwalte182bfe2013-07-16 12:06:09 -07002354
2355 /**
Wink Saville42d4f082013-07-20 20:31:59 -07002356 * Get the mobile provisioning url.
Robert Greenwalte182bfe2013-07-16 12:06:09 -07002357 * {@hide}
2358 */
2359 public String getMobileProvisioningUrl() {
2360 try {
2361 return mService.getMobileProvisioningUrl();
2362 } catch (RemoteException e) {
2363 }
2364 return null;
2365 }
Wink Saville42d4f082013-07-20 20:31:59 -07002366
2367 /**
Wink Saville948282b2013-08-29 08:55:16 -07002368 * Set sign in error notification to visible or in visible
2369 *
2370 * @param visible
2371 * @param networkType
2372 *
2373 * {@hide}
Paul Jensen3541e9f2015-03-18 12:23:02 -04002374 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
Wink Saville948282b2013-08-29 08:55:16 -07002375 */
2376 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04002377 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07002378 try {
Paul Jensen89e0f092014-09-15 15:59:36 -04002379 mService.setProvisioningNotificationVisible(visible, networkType, action);
Wink Saville948282b2013-08-29 08:55:16 -07002380 } catch (RemoteException e) {
2381 }
2382 }
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07002383
2384 /**
2385 * Set the value for enabling/disabling airplane mode
Paul Jensenb2748922015-05-06 11:10:18 -04002386 * <p>This method requires the caller to hold the permission
2387 * {@link android.Manifest.permission#CONNECTIVITY_INTERNAL}.
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07002388 *
2389 * @param enable whether to enable airplane mode or not
2390 *
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07002391 * @hide
2392 */
2393 public void setAirplaneMode(boolean enable) {
2394 try {
2395 mService.setAirplaneMode(enable);
2396 } catch (RemoteException e) {
2397 }
2398 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002399
2400 /** {@hide} */
Robert Greenwalta67be032014-05-16 15:49:14 -07002401 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07002402 try {
Robert Greenwalta67be032014-05-16 15:49:14 -07002403 mService.registerNetworkFactory(messenger, name);
2404 } catch (RemoteException e) { }
2405 }
2406
2407 /** {@hide} */
2408 public void unregisterNetworkFactory(Messenger messenger) {
2409 try {
2410 mService.unregisterNetworkFactory(messenger);
Robert Greenwalte049c232014-04-11 15:53:27 -07002411 } catch (RemoteException e) { }
2412 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002413
Paul Jensen31a94f42015-02-13 14:18:39 -05002414 /**
2415 * @hide
2416 * Register a NetworkAgent with ConnectivityService.
2417 * @return NetID corresponding to NetworkAgent.
2418 */
2419 public int registerNetworkAgent(Messenger messenger, NetworkInfo ni, LinkProperties lp,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07002420 NetworkCapabilities nc, int score, NetworkMisc misc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002421 try {
Paul Jensen31a94f42015-02-13 14:18:39 -05002422 return mService.registerNetworkAgent(messenger, ni, lp, nc, score, misc);
2423 } catch (RemoteException e) {
2424 return NETID_UNSET;
2425 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002426 }
2427
Robert Greenwalt9258c642014-03-26 16:47:06 -07002428 /**
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002429 * Base class for NetworkRequest callbacks. Used for notifications about network
2430 * changes. Should be extended by applications wanting notifications.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002431 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07002432 public static class NetworkCallback {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002433 /**
Lorenzo Colitti07086932015-04-24 12:23:24 +09002434 * Called when the framework connects to a new network to evaluate whether it satisfies this
2435 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
2436 * callback. There is no guarantee that this new network will satisfy any requests, or that
2437 * the network will stay connected for longer than the time necessary to evaluate it.
2438 * <p>
2439 * Most applications <b>should not</b> act on this callback, and should instead use
2440 * {@link #onAvailable}. This callback is intended for use by applications that can assist
2441 * the framework in properly evaluating the network &mdash; for example, an application that
2442 * can automatically log in to a captive portal without user intervention.
2443 *
2444 * @param network The {@link Network} of the network that is being evaluated.
Lorenzo Colitti66276122015-06-11 14:27:17 +09002445 *
2446 * @hide
Robert Greenwalt7b816022014-04-18 15:25:25 -07002447 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07002448 public void onPreCheck(Network network) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07002449
2450 /**
Lorenzo Colitti07086932015-04-24 12:23:24 +09002451 * Called when the framework connects and has declared a new network ready for use.
Robert Greenwalt6078b502014-06-11 16:05:07 -07002452 * This callback may be called more than once if the {@link Network} that is
2453 * satisfying the request changes.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002454 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002455 * @param network The {@link Network} of the satisfying network.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002456 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07002457 public void onAvailable(Network network) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07002458
2459 /**
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002460 * Called when the network is about to be disconnected. Often paired with an
Robert Greenwalt6078b502014-06-11 16:05:07 -07002461 * {@link NetworkCallback#onAvailable} call with the new replacement network
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002462 * for graceful handover. This may not be called if we have a hard loss
2463 * (loss without warning). This may be followed by either a
Robert Greenwalt6078b502014-06-11 16:05:07 -07002464 * {@link NetworkCallback#onLost} call or a
2465 * {@link NetworkCallback#onAvailable} call for this network depending
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002466 * on whether we lose or regain it.
2467 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07002468 * @param network The {@link Network} that is about to be disconnected.
2469 * @param maxMsToLive The time in ms the framework will attempt to keep the
2470 * network connected. Note that the network may suffer a
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002471 * hard loss at any time.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002472 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07002473 public void onLosing(Network network, int maxMsToLive) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07002474
2475 /**
2476 * Called when the framework has a hard loss of the network or when the
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002477 * graceful failure ends.
2478 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002479 * @param network The {@link Network} lost.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002480 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07002481 public void onLost(Network network) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07002482
2483 /**
2484 * Called if no network is found in the given timeout time. If no timeout is given,
2485 * this will not be called.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002486 * @hide
Robert Greenwalt7b816022014-04-18 15:25:25 -07002487 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07002488 public void onUnavailable() {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07002489
2490 /**
2491 * Called when the network the framework connected to for this request
2492 * changes capabilities but still satisfies the stated need.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002493 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002494 * @param network The {@link Network} whose capabilities have changed.
Lorenzo Colittie285b432015-04-23 15:32:42 +09002495 * @param networkCapabilities The new {@link android.net.NetworkCapabilities} for this network.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002496 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07002497 public void onCapabilitiesChanged(Network network,
Robert Greenwalt7b816022014-04-18 15:25:25 -07002498 NetworkCapabilities networkCapabilities) {}
2499
2500 /**
2501 * Called when the network the framework connected to for this request
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002502 * changes {@link LinkProperties}.
2503 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002504 * @param network The {@link Network} whose link properties have changed.
2505 * @param linkProperties The new {@link LinkProperties} for this network.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002506 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07002507 public void onLinkPropertiesChanged(Network network, LinkProperties linkProperties) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07002508
Robert Greenwalt8d482522015-06-24 13:23:42 -07002509 /**
2510 * Called when the network the framework connected to for this request
2511 * goes into {@link NetworkInfo.DetailedState.SUSPENDED}.
2512 * This generally means that while the TCP connections are still live,
2513 * temporarily network data fails to transfer. Specifically this is used
2514 * on cellular networks to mask temporary outages when driving through
2515 * a tunnel, etc.
2516 * @hide
2517 */
2518 public void onNetworkSuspended(Network network) {}
2519
2520 /**
2521 * Called when the network the framework connected to for this request
2522 * returns from a {@link NetworkInfo.DetailedState.SUSPENDED} state.
2523 * This should always be preceeded by a matching {@code onNetworkSuspended}
2524 * call.
2525 * @hide
2526 */
2527 public void onNetworkResumed(Network network) {}
2528
Robert Greenwalt6078b502014-06-11 16:05:07 -07002529 private NetworkRequest networkRequest;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002530 }
2531
Robert Greenwalt9258c642014-03-26 16:47:06 -07002532 private static final int BASE = Protocol.BASE_CONNECTIVITY_MANAGER;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002533 /** @hide */
Robert Greenwalt8d482522015-06-24 13:23:42 -07002534 public static final int CALLBACK_PRECHECK = BASE + 1;
2535 /** @hide */
2536 public static final int CALLBACK_AVAILABLE = BASE + 2;
2537 /** @hide arg1 = TTL */
2538 public static final int CALLBACK_LOSING = BASE + 3;
2539 /** @hide */
2540 public static final int CALLBACK_LOST = BASE + 4;
2541 /** @hide */
2542 public static final int CALLBACK_UNAVAIL = BASE + 5;
2543 /** @hide */
2544 public static final int CALLBACK_CAP_CHANGED = BASE + 6;
2545 /** @hide */
2546 public static final int CALLBACK_IP_CHANGED = BASE + 7;
2547 /** @hide */
2548 public static final int CALLBACK_RELEASED = BASE + 8;
2549 /** @hide */
2550 public static final int CALLBACK_EXIT = BASE + 9;
Robert Greenwalt562cc542014-05-15 18:07:26 -07002551 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Robert Greenwalt8d482522015-06-24 13:23:42 -07002552 private static final int EXPIRE_LEGACY_REQUEST = BASE + 10;
2553 /** @hide */
2554 public static final int CALLBACK_SUSPENDED = BASE + 11;
2555 /** @hide */
2556 public static final int CALLBACK_RESUMED = BASE + 12;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002557
Robert Greenwalt562cc542014-05-15 18:07:26 -07002558 private class CallbackHandler extends Handler {
Robert Greenwalt6078b502014-06-11 16:05:07 -07002559 private final HashMap<NetworkRequest, NetworkCallback>mCallbackMap;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002560 private final AtomicInteger mRefCount;
2561 private static final String TAG = "ConnectivityManager.CallbackHandler";
2562 private final ConnectivityManager mCm;
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07002563 private static final boolean DBG = false;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002564
Robert Greenwalt6078b502014-06-11 16:05:07 -07002565 CallbackHandler(Looper looper, HashMap<NetworkRequest, NetworkCallback>callbackMap,
Robert Greenwalt9258c642014-03-26 16:47:06 -07002566 AtomicInteger refCount, ConnectivityManager cm) {
2567 super(looper);
2568 mCallbackMap = callbackMap;
2569 mRefCount = refCount;
2570 mCm = cm;
2571 }
2572
2573 @Override
2574 public void handleMessage(Message message) {
Lorenzo Colittidb95a602015-04-24 15:21:21 +09002575 NetworkRequest request = (NetworkRequest) getObject(message, NetworkRequest.class);
2576 Network network = (Network) getObject(message, Network.class);
Lorenzo Colittifcfa7d92016-03-01 22:56:37 +09002577 if (DBG) {
2578 Log.d(TAG, whatToString(message.what) + " for network " + network);
2579 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002580 switch (message.what) {
2581 case CALLBACK_PRECHECK: {
Lorenzo Colittidb95a602015-04-24 15:21:21 +09002582 NetworkCallback callback = getCallback(request, "PRECHECK");
2583 if (callback != null) {
2584 callback.onPreCheck(network);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002585 }
2586 break;
2587 }
2588 case CALLBACK_AVAILABLE: {
Lorenzo Colittidb95a602015-04-24 15:21:21 +09002589 NetworkCallback callback = getCallback(request, "AVAILABLE");
2590 if (callback != null) {
2591 callback.onAvailable(network);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002592 }
2593 break;
2594 }
2595 case CALLBACK_LOSING: {
Lorenzo Colittidb95a602015-04-24 15:21:21 +09002596 NetworkCallback callback = getCallback(request, "LOSING");
2597 if (callback != null) {
2598 callback.onLosing(network, message.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002599 }
2600 break;
2601 }
2602 case CALLBACK_LOST: {
Lorenzo Colittidb95a602015-04-24 15:21:21 +09002603 NetworkCallback callback = getCallback(request, "LOST");
2604 if (callback != null) {
2605 callback.onLost(network);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002606 }
2607 break;
2608 }
2609 case CALLBACK_UNAVAIL: {
Lorenzo Colittidb95a602015-04-24 15:21:21 +09002610 NetworkCallback callback = getCallback(request, "UNAVAIL");
2611 if (callback != null) {
2612 callback.onUnavailable();
Robert Greenwalt9258c642014-03-26 16:47:06 -07002613 }
2614 break;
2615 }
2616 case CALLBACK_CAP_CHANGED: {
Lorenzo Colittidb95a602015-04-24 15:21:21 +09002617 NetworkCallback callback = getCallback(request, "CAP_CHANGED");
2618 if (callback != null) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07002619 NetworkCapabilities cap = (NetworkCapabilities)getObject(message,
2620 NetworkCapabilities.class);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002621
Lorenzo Colittidb95a602015-04-24 15:21:21 +09002622 callback.onCapabilitiesChanged(network, cap);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002623 }
2624 break;
2625 }
2626 case CALLBACK_IP_CHANGED: {
Lorenzo Colittidb95a602015-04-24 15:21:21 +09002627 NetworkCallback callback = getCallback(request, "IP_CHANGED");
2628 if (callback != null) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07002629 LinkProperties lp = (LinkProperties)getObject(message,
2630 LinkProperties.class);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002631
Lorenzo Colittidb95a602015-04-24 15:21:21 +09002632 callback.onLinkPropertiesChanged(network, lp);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002633 }
2634 break;
2635 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07002636 case CALLBACK_SUSPENDED: {
2637 NetworkCallback callback = getCallback(request, "SUSPENDED");
2638 if (callback != null) {
2639 callback.onNetworkSuspended(network);
2640 }
2641 break;
2642 }
2643 case CALLBACK_RESUMED: {
2644 NetworkCallback callback = getCallback(request, "RESUMED");
2645 if (callback != null) {
2646 callback.onNetworkResumed(network);
2647 }
2648 break;
2649 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002650 case CALLBACK_RELEASED: {
Lorenzo Colittidb95a602015-04-24 15:21:21 +09002651 NetworkCallback callback = null;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002652 synchronized(mCallbackMap) {
Lorenzo Colittidb95a602015-04-24 15:21:21 +09002653 callback = mCallbackMap.remove(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002654 }
Lorenzo Colittidb95a602015-04-24 15:21:21 +09002655 if (callback != null) {
Robert Greenwalt6078b502014-06-11 16:05:07 -07002656 synchronized(mRefCount) {
2657 if (mRefCount.decrementAndGet() == 0) {
2658 getLooper().quit();
2659 }
2660 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002661 } else {
Lorenzo Colittidb95a602015-04-24 15:21:21 +09002662 Log.e(TAG, "callback not found for RELEASED message");
Robert Greenwalt9258c642014-03-26 16:47:06 -07002663 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002664 break;
2665 }
2666 case CALLBACK_EXIT: {
Lorenzo Colittidb95a602015-04-24 15:21:21 +09002667 Log.d(TAG, "Listener quitting");
Robert Greenwalt9258c642014-03-26 16:47:06 -07002668 getLooper().quit();
2669 break;
2670 }
Robert Greenwalt562cc542014-05-15 18:07:26 -07002671 case EXPIRE_LEGACY_REQUEST: {
2672 expireRequest((NetworkCapabilities)message.obj, message.arg1);
2673 break;
2674 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002675 }
2676 }
2677
Robert Greenwalta848c1c2014-09-30 16:50:07 -07002678 private Object getObject(Message msg, Class c) {
2679 return msg.getData().getParcelable(c.getSimpleName());
Robert Greenwalt9258c642014-03-26 16:47:06 -07002680 }
Lorenzo Colittidb95a602015-04-24 15:21:21 +09002681
2682 private NetworkCallback getCallback(NetworkRequest req, String name) {
2683 NetworkCallback callback;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002684 synchronized(mCallbackMap) {
Lorenzo Colittidb95a602015-04-24 15:21:21 +09002685 callback = mCallbackMap.get(req);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002686 }
Lorenzo Colittidb95a602015-04-24 15:21:21 +09002687 if (callback == null) {
2688 Log.e(TAG, "callback not found for " + name + " message");
2689 }
2690 return callback;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002691 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002692 }
2693
Robert Greenwalt6078b502014-06-11 16:05:07 -07002694 private void incCallbackHandlerRefCount() {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002695 synchronized(sCallbackRefCount) {
2696 if (sCallbackRefCount.incrementAndGet() == 1) {
2697 // TODO - switch this over to a ManagerThread or expire it when done
2698 HandlerThread callbackThread = new HandlerThread("ConnectivityManager");
2699 callbackThread.start();
2700 sCallbackHandler = new CallbackHandler(callbackThread.getLooper(),
Robert Greenwalt6078b502014-06-11 16:05:07 -07002701 sNetworkCallback, sCallbackRefCount, this);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002702 }
2703 }
2704 }
2705
Robert Greenwalt6078b502014-06-11 16:05:07 -07002706 private void decCallbackHandlerRefCount() {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002707 synchronized(sCallbackRefCount) {
2708 if (sCallbackRefCount.decrementAndGet() == 0) {
2709 sCallbackHandler.obtainMessage(CALLBACK_EXIT).sendToTarget();
2710 sCallbackHandler = null;
2711 }
2712 }
2713 }
2714
Robert Greenwalt6078b502014-06-11 16:05:07 -07002715 static final HashMap<NetworkRequest, NetworkCallback> sNetworkCallback =
2716 new HashMap<NetworkRequest, NetworkCallback>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07002717 static final AtomicInteger sCallbackRefCount = new AtomicInteger(0);
2718 static CallbackHandler sCallbackHandler = null;
2719
2720 private final static int LISTEN = 1;
2721 private final static int REQUEST = 2;
2722
Robert Greenwalt562cc542014-05-15 18:07:26 -07002723 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need,
Robert Greenwalt6078b502014-06-11 16:05:07 -07002724 NetworkCallback networkCallback, int timeoutSec, int action,
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07002725 int legacyType) {
Robert Greenwalt6078b502014-06-11 16:05:07 -07002726 if (networkCallback == null) {
2727 throw new IllegalArgumentException("null NetworkCallback");
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002728 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002729 if (need == null) throw new IllegalArgumentException("null NetworkCapabilities");
2730 try {
Robert Greenwalt6078b502014-06-11 16:05:07 -07002731 incCallbackHandlerRefCount();
Paul Jensen7221cc32014-06-27 11:05:32 -04002732 synchronized(sNetworkCallback) {
2733 if (action == LISTEN) {
2734 networkCallback.networkRequest = mService.listenForNetwork(need,
2735 new Messenger(sCallbackHandler), new Binder());
2736 } else {
2737 networkCallback.networkRequest = mService.requestNetwork(need,
2738 new Messenger(sCallbackHandler), timeoutSec, new Binder(), legacyType);
2739 }
2740 if (networkCallback.networkRequest != null) {
Robert Greenwalt6078b502014-06-11 16:05:07 -07002741 sNetworkCallback.put(networkCallback.networkRequest, networkCallback);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002742 }
2743 }
2744 } catch (RemoteException e) {}
Robert Greenwalt6078b502014-06-11 16:05:07 -07002745 if (networkCallback.networkRequest == null) decCallbackHandlerRefCount();
2746 return networkCallback.networkRequest;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002747 }
2748
2749 /**
Lorenzo Colitti7de289f2015-11-25 12:00:52 +09002750 * Helper function to requests a network with a particular legacy type.
2751 *
2752 * This is temporarily public @hide so it can be called by system code that uses the
2753 * NetworkRequest API to request networks but relies on CONNECTIVITY_ACTION broadcasts for
2754 * instead network notifications.
2755 *
2756 * TODO: update said system code to rely on NetworkCallbacks and make this method private.
2757 *
2758 * @hide
2759 */
Lorenzo Colittid1179462015-11-25 15:47:14 +09002760 public void requestNetwork(NetworkRequest request, NetworkCallback networkCallback,
Lorenzo Colitti7de289f2015-11-25 12:00:52 +09002761 int timeoutMs, int legacyType) {
Lorenzo Colittid1179462015-11-25 15:47:14 +09002762 sendRequestForNetwork(request.networkCapabilities, networkCallback, timeoutMs, REQUEST,
2763 legacyType);
Lorenzo Colitti7de289f2015-11-25 12:00:52 +09002764 }
2765
2766 /**
Lorenzo Colittie285b432015-04-23 15:32:42 +09002767 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002768 *
2769 * This {@link NetworkRequest} will live until released via
Robert Greenwalt6078b502014-06-11 16:05:07 -07002770 * {@link #unregisterNetworkCallback} or the calling application exits.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002771 * Status of the request can be followed by listening to the various
Robert Greenwalt6078b502014-06-11 16:05:07 -07002772 * callbacks described in {@link NetworkCallback}. The {@link Network}
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002773 * can be used to direct traffic to the network.
Paul Jensenbb2e0e92015-06-16 15:11:58 -04002774 * <p>It is presently unsupported to request a network with mutable
2775 * {@link NetworkCapabilities} such as
2776 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
2777 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
2778 * as these {@code NetworkCapabilities} represent states that a particular
2779 * network may never attain, and whether a network will attain these states
2780 * is unknown prior to bringing up the network so the framework does not
2781 * know how to go about satisfing a request with these capabilities.
Lorenzo Colittid5427052015-10-15 16:29:00 +09002782 *
2783 * <p>This method requires the caller to hold either the
2784 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2785 * or the ability to modify system settings as determined by
2786 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt9258c642014-03-26 16:47:06 -07002787 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07002788 * @param request {@link NetworkRequest} describing this request.
2789 * @param networkCallback The {@link NetworkCallback} to be utilized for this
2790 * request. Note the callback must not be shared - they
2791 * uniquely specify this request.
Paul Jensenbb2e0e92015-06-16 15:11:58 -04002792 * @throws IllegalArgumentException if {@code request} specifies any mutable
2793 * {@code NetworkCapabilities}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002794 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07002795 public void requestNetwork(NetworkRequest request, NetworkCallback networkCallback) {
Lorenzo Colittid1179462015-11-25 15:47:14 +09002796 requestNetwork(request, networkCallback, 0,
Lorenzo Colitti7de289f2015-11-25 12:00:52 +09002797 inferLegacyTypeForNetworkCapabilities(request.networkCapabilities));
Robert Greenwalt9258c642014-03-26 16:47:06 -07002798 }
2799
2800 /**
Lorenzo Colittie285b432015-04-23 15:32:42 +09002801 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
Robert Greenwalt9258c642014-03-26 16:47:06 -07002802 * by a timeout.
2803 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002804 * This function behaves identically to the non-timedout version, but if a suitable
Robert Greenwalt6078b502014-06-11 16:05:07 -07002805 * network is not found within the given time (in milliseconds) the
2806 * {@link NetworkCallback#unavailable} callback is called. The request must
Lorenzo Colitti36728a92015-11-26 11:03:17 +09002807 * still be released normally by calling {@link unregisterNetworkCallback}.
Lorenzo Colittid5427052015-10-15 16:29:00 +09002808 *
2809 * <p>This method requires the caller to hold either the
2810 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2811 * or the ability to modify system settings as determined by
2812 * {@link android.provider.Settings.System#canWrite}.</p>
2813 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07002814 * @param request {@link NetworkRequest} describing this request.
2815 * @param networkCallback The callbacks to be utilized for this request. Note
2816 * the callbacks must not be shared - they uniquely specify
2817 * this request.
2818 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
2819 * before {@link NetworkCallback#unavailable} is called.
Lorenzo Colitti7de289f2015-11-25 12:00:52 +09002820 *
2821 * TODO: Make timeouts work and then unhide this method.
2822 *
Robert Greenwalt9258c642014-03-26 16:47:06 -07002823 * @hide
2824 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07002825 public void requestNetwork(NetworkRequest request, NetworkCallback networkCallback,
2826 int timeoutMs) {
Lorenzo Colittid1179462015-11-25 15:47:14 +09002827 requestNetwork(request, networkCallback, timeoutMs,
Lorenzo Colitti7de289f2015-11-25 12:00:52 +09002828 inferLegacyTypeForNetworkCapabilities(request.networkCapabilities));
Robert Greenwalt9258c642014-03-26 16:47:06 -07002829 }
2830
2831 /**
Robert Greenwalt6078b502014-06-11 16:05:07 -07002832 * The maximum number of milliseconds the framework will look for a suitable network
Robert Greenwalt9258c642014-03-26 16:47:06 -07002833 * during a timeout-equiped call to {@link requestNetwork}.
2834 * {@hide}
2835 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07002836 public final static int MAX_NETWORK_REQUEST_TIMEOUT_MS = 100 * 60 * 1000;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002837
2838 /**
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002839 * The lookup key for a {@link Network} object included with the intent after
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002840 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002841 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeremy Joslinfcde58f2015-02-11 16:51:13 -08002842 * <p>
Paul Jensen72db88e2015-03-10 10:54:12 -04002843 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
2844 * then you must get a ConnectivityManager instance before doing so.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002845 */
Erik Kline90e93072014-11-19 12:12:24 +09002846 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002847
2848 /**
Robert Greenwalt6078b502014-06-11 16:05:07 -07002849 * The lookup key for a {@link NetworkRequest} object included with the intent after
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002850 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002851 * {@link android.content.Intent#getParcelableExtra(String)}.
2852 */
Erik Kline90e93072014-11-19 12:12:24 +09002853 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002854
2855
2856 /**
Lorenzo Colittie285b432015-04-23 15:32:42 +09002857 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002858 *
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002859 * This function behaves identically to the version that takes a NetworkCallback, but instead
Robert Greenwalt6078b502014-06-11 16:05:07 -07002860 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002861 * the request may outlive the calling application and get called back when a suitable
2862 * network is found.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002863 * <p>
2864 * The operation is an Intent broadcast that goes to a broadcast receiver that
2865 * you registered with {@link Context#registerReceiver} or through the
2866 * &lt;receiver&gt; tag in an AndroidManifest.xml file
2867 * <p>
2868 * The operation Intent is delivered with two extras, a {@link Network} typed
Erik Kline90e93072014-11-19 12:12:24 +09002869 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
2870 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
Robert Greenwalt9258c642014-03-26 16:47:06 -07002871 * the original requests parameters. It is important to create a new,
Robert Greenwalt6078b502014-06-11 16:05:07 -07002872 * {@link NetworkCallback} based request before completing the processing of the
Robert Greenwalt9258c642014-03-26 16:47:06 -07002873 * Intent to reserve the network or it will be released shortly after the Intent
2874 * is processed.
2875 * <p>
Paul Jensen694f2b82015-06-17 14:15:39 -04002876 * If there is already a request for this Intent registered (with the equality of
Robert Greenwalt9258c642014-03-26 16:47:06 -07002877 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002878 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002879 * <p>
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002880 * The request may be released normally by calling
2881 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
Paul Jensenbb2e0e92015-06-16 15:11:58 -04002882 * <p>It is presently unsupported to request a network with either
2883 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
2884 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
2885 * as these {@code NetworkCapabilities} represent states that a particular
2886 * network may never attain, and whether a network will attain these states
2887 * is unknown prior to bringing up the network so the framework does not
2888 * know how to go about satisfing a request with these capabilities.
Lorenzo Colittid5427052015-10-15 16:29:00 +09002889 *
2890 * <p>This method requires the caller to hold either the
2891 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2892 * or the ability to modify system settings as determined by
2893 * {@link android.provider.Settings.System#canWrite}.</p>
2894 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07002895 * @param request {@link NetworkRequest} describing this request.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002896 * @param operation Action to perform when the network is available (corresponds
Robert Greenwalt6078b502014-06-11 16:05:07 -07002897 * to the {@link NetworkCallback#onAvailable} call. Typically
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002898 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Paul Jensenbb2e0e92015-06-16 15:11:58 -04002899 * @throws IllegalArgumentException if {@code request} contains either
2900 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
2901 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002902 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07002903 public void requestNetwork(NetworkRequest request, PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002904 checkPendingIntent(operation);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002905 try {
Robert Greenwalt6078b502014-06-11 16:05:07 -07002906 mService.pendingRequestForNetwork(request.networkCapabilities, operation);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002907 } catch (RemoteException e) {}
Robert Greenwalt9258c642014-03-26 16:47:06 -07002908 }
2909
2910 /**
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002911 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
2912 * <p>
2913 * This method has the same behavior as {@link #unregisterNetworkCallback} with respect to
2914 * releasing network resources and disconnecting.
2915 *
2916 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
2917 * PendingIntent passed to
2918 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
2919 * corresponding NetworkRequest you'd like to remove. Cannot be null.
2920 */
2921 public void releaseNetworkRequest(PendingIntent operation) {
2922 checkPendingIntent(operation);
2923 try {
2924 mService.releasePendingNetworkRequest(operation);
2925 } catch (RemoteException e) {}
2926 }
2927
2928 private void checkPendingIntent(PendingIntent intent) {
2929 if (intent == null) {
2930 throw new IllegalArgumentException("PendingIntent cannot be null.");
2931 }
2932 }
2933
2934 /**
Robert Greenwalt9258c642014-03-26 16:47:06 -07002935 * Registers to receive notifications about all networks which satisfy the given
Robert Greenwalt6078b502014-06-11 16:05:07 -07002936 * {@link NetworkRequest}. The callbacks will continue to be called until
2937 * either the application exits or {@link #unregisterNetworkCallback} is called
Paul Jensenb2748922015-05-06 11:10:18 -04002938 * <p>This method requires the caller to hold the permission
2939 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002940 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07002941 * @param request {@link NetworkRequest} describing this request.
2942 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
2943 * networks change state.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002944 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07002945 public void registerNetworkCallback(NetworkRequest request, NetworkCallback networkCallback) {
2946 sendRequestForNetwork(request.networkCapabilities, networkCallback, 0, LISTEN, TYPE_NONE);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002947 }
2948
2949 /**
Paul Jensen694f2b82015-06-17 14:15:39 -04002950 * Registers a PendingIntent to be sent when a network is available which satisfies the given
2951 * {@link NetworkRequest}.
2952 *
2953 * This function behaves identically to the version that takes a NetworkCallback, but instead
2954 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
2955 * the request may outlive the calling application and get called back when a suitable
2956 * network is found.
2957 * <p>
2958 * The operation is an Intent broadcast that goes to a broadcast receiver that
2959 * you registered with {@link Context#registerReceiver} or through the
2960 * &lt;receiver&gt; tag in an AndroidManifest.xml file
2961 * <p>
2962 * The operation Intent is delivered with two extras, a {@link Network} typed
2963 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
2964 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
2965 * the original requests parameters.
2966 * <p>
2967 * If there is already a request for this Intent registered (with the equality of
2968 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
2969 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
2970 * <p>
2971 * The request may be released normally by calling
Paul Jensenf2c1cfe2015-06-30 14:29:18 -04002972 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
Paul Jensen694f2b82015-06-17 14:15:39 -04002973 * <p>This method requires the caller to hold the permission
2974 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
2975 * @param request {@link NetworkRequest} describing this request.
2976 * @param operation Action to perform when the network is available (corresponds
2977 * to the {@link NetworkCallback#onAvailable} call. Typically
2978 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
2979 */
2980 public void registerNetworkCallback(NetworkRequest request, PendingIntent operation) {
2981 checkPendingIntent(operation);
2982 try {
2983 mService.pendingListenForNetwork(request.networkCapabilities, operation);
2984 } catch (RemoteException e) {}
2985 }
2986
2987 /**
fengludb571472015-04-21 17:12:05 -07002988 * Requests bandwidth update for a given {@link Network} and returns whether the update request
2989 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
2990 * network connection for updated bandwidth information. The caller will be notified via
2991 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
2992 * method assumes that the caller has previously called {@link #registerNetworkCallback} to
2993 * listen for network changes.
fenglub15e72b2015-03-20 11:29:56 -07002994 *
fengluae519192015-04-27 14:28:04 -07002995 * @param network {@link Network} specifying which network you're interested.
fengludb571472015-04-21 17:12:05 -07002996 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
fenglub15e72b2015-03-20 11:29:56 -07002997 */
fengludb571472015-04-21 17:12:05 -07002998 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07002999 try {
fengludb571472015-04-21 17:12:05 -07003000 return mService.requestBandwidthUpdate(network);
fenglub15e72b2015-03-20 11:29:56 -07003001 } catch (RemoteException e) {
3002 return false;
3003 }
3004 }
3005
3006 /**
Robert Greenwalt6078b502014-06-11 16:05:07 -07003007 * Unregisters callbacks about and possibly releases networks originating from
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +09003008 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and {@link #registerNetworkCallback}
3009 * calls. If the given {@code NetworkCallback} had previously been used with
3010 * {@code #requestNetwork}, any networks that had been connected to only to satisfy that request
3011 * will be disconnected.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003012 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07003013 * @param networkCallback The {@link NetworkCallback} used when making the request.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003014 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07003015 public void unregisterNetworkCallback(NetworkCallback networkCallback) {
3016 if (networkCallback == null || networkCallback.networkRequest == null ||
3017 networkCallback.networkRequest.requestId == REQUEST_ID_UNSET) {
3018 throw new IllegalArgumentException("Invalid NetworkCallback");
3019 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003020 try {
Robert Greenwalt6078b502014-06-11 16:05:07 -07003021 mService.releaseNetworkRequest(networkCallback.networkRequest);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003022 } catch (RemoteException e) {}
3023 }
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04003024
3025 /**
Paul Jensenf2c1cfe2015-06-30 14:29:18 -04003026 * Unregisters a callback previously registered via
3027 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
3028 *
3029 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
3030 * PendingIntent passed to
3031 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
3032 * Cannot be null.
3033 */
3034 public void unregisterNetworkCallback(PendingIntent operation) {
3035 releaseNetworkRequest(operation);
3036 }
3037
3038 /**
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003039 * Informs the system whether it should switch to {@code network} regardless of whether it is
3040 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
3041 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
3042 * the system default network regardless of any other network that's currently connected. If
3043 * {@code always} is true, then the choice is remembered, so that the next time the user
3044 * connects to this network, the system will switch to it.
3045 *
3046 * <p>This method requires the caller to hold the permission
3047 * {@link android.Manifest.permission#CONNECTIVITY_INTERNAL}
3048 *
3049 * @param network The network to accept.
3050 * @param accept Whether to accept the network even if unvalidated.
3051 * @param always Whether to remember this choice in the future.
3052 *
3053 * @hide
3054 */
3055 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
3056 try {
3057 mService.setAcceptUnvalidated(network, accept, always);
3058 } catch (RemoteException e) {}
3059 }
3060
3061 /**
Stuart Scott984dc852015-03-30 13:17:11 -07003062 * Resets all connectivity manager settings back to factory defaults.
3063 * @hide
3064 */
3065 public void factoryReset() {
Stuart Scott984dc852015-03-30 13:17:11 -07003066 try {
Stuart Scottf1fb3972015-04-02 18:00:02 -07003067 mService.factoryReset();
Stuart Scott984dc852015-03-30 13:17:11 -07003068 } catch (RemoteException e) {
Stuart Scott984dc852015-03-30 13:17:11 -07003069 }
3070 }
3071
3072 /**
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04003073 * Binds the current process to {@code network}. All Sockets created in the future
3074 * (and not explicitly bound via a bound SocketFactory from
3075 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
3076 * {@code network}. All host name resolutions will be limited to {@code network} as well.
3077 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
3078 * work and all host name resolutions will fail. This is by design so an application doesn't
3079 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
3080 * To clear binding pass {@code null} for {@code network}. Using individually bound
3081 * Sockets created by Network.getSocketFactory().createSocket() and
3082 * performing network-specific host name resolutions via
3083 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
Paul Jensen72db88e2015-03-10 10:54:12 -04003084 * {@code bindProcessToNetwork}.
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04003085 *
3086 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
3087 * the current binding.
3088 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
3089 */
Paul Jensen72db88e2015-03-10 10:54:12 -04003090 public boolean bindProcessToNetwork(Network network) {
3091 // Forcing callers to call thru non-static function ensures ConnectivityManager
3092 // instantiated.
3093 return setProcessDefaultNetwork(network);
3094 }
3095
3096 /**
3097 * Binds the current process to {@code network}. All Sockets created in the future
3098 * (and not explicitly bound via a bound SocketFactory from
3099 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
3100 * {@code network}. All host name resolutions will be limited to {@code network} as well.
3101 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
3102 * work and all host name resolutions will fail. This is by design so an application doesn't
3103 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
3104 * To clear binding pass {@code null} for {@code network}. Using individually bound
3105 * Sockets created by Network.getSocketFactory().createSocket() and
3106 * performing network-specific host name resolutions via
3107 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
3108 * {@code setProcessDefaultNetwork}.
3109 *
3110 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
3111 * the current binding.
3112 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
3113 * @deprecated This function can throw {@link IllegalStateException}. Use
3114 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
3115 * is a direct replacement.
3116 */
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04003117 public static boolean setProcessDefaultNetwork(Network network) {
Paul Jensenc91b5342014-08-27 12:38:45 -04003118 int netId = (network == null) ? NETID_UNSET : network.netId;
Paul Jensen72db88e2015-03-10 10:54:12 -04003119 if (netId == NetworkUtils.getBoundNetworkForProcess()) {
Paul Jensenc91b5342014-08-27 12:38:45 -04003120 return true;
3121 }
3122 if (NetworkUtils.bindProcessToNetwork(netId)) {
Paul Jensene0bef712014-12-10 15:12:18 -05003123 // Set HTTP proxy system properties to match network.
3124 // TODO: Deprecate this static method and replace it with a non-static version.
Lorenzo Colittiec4c5552015-04-22 11:52:48 +09003125 try {
3126 Proxy.setHttpProxySystemProperty(getInstance().getDefaultProxy());
3127 } catch (SecurityException e) {
3128 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
3129 Log.e(TAG, "Can't set proxy properties", e);
3130 }
Paul Jensenc91b5342014-08-27 12:38:45 -04003131 // Must flush DNS cache as new network may have different DNS resolutions.
3132 InetAddress.clearDnsCache();
3133 // Must flush socket pool as idle sockets will be bound to previous network and may
3134 // cause subsequent fetches to be performed on old network.
3135 NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
3136 return true;
3137 } else {
3138 return false;
3139 }
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04003140 }
3141
3142 /**
3143 * Returns the {@link Network} currently bound to this process via
Paul Jensen72db88e2015-03-10 10:54:12 -04003144 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04003145 *
3146 * @return {@code Network} to which this process is bound, or {@code null}.
3147 */
Paul Jensen72db88e2015-03-10 10:54:12 -04003148 public Network getBoundNetworkForProcess() {
3149 // Forcing callers to call thru non-static function ensures ConnectivityManager
3150 // instantiated.
3151 return getProcessDefaultNetwork();
3152 }
3153
3154 /**
3155 * Returns the {@link Network} currently bound to this process via
3156 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
3157 *
3158 * @return {@code Network} to which this process is bound, or {@code null}.
3159 * @deprecated Using this function can lead to other functions throwing
3160 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
3161 * {@code getBoundNetworkForProcess} is a direct replacement.
3162 */
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04003163 public static Network getProcessDefaultNetwork() {
Paul Jensen72db88e2015-03-10 10:54:12 -04003164 int netId = NetworkUtils.getBoundNetworkForProcess();
Paul Jensenbcc76d32014-07-11 08:17:29 -04003165 if (netId == NETID_UNSET) return null;
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04003166 return new Network(netId);
3167 }
3168
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09003169 private void unsupportedStartingFrom(int version) {
3170 if (Process.myUid() == Process.SYSTEM_UID) {
3171 // The getApplicationInfo() call we make below is not supported in system context, and
3172 // we want to allow the system to use these APIs anyway.
3173 return;
3174 }
3175
3176 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
3177 throw new UnsupportedOperationException(
3178 "This method is not supported in target SDK version " + version + " and above");
3179 }
3180 }
3181
3182 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
3183 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
Lifu Tang30f95a72016-01-07 23:20:38 -08003184 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09003185 // remove these exemptions. Note that this check is not secure, and apps can still access these
3186 // functions by accessing ConnectivityService directly. However, it should be clear that doing
3187 // so is unsupported and may break in the future. http://b/22728205
3188 private void checkLegacyRoutingApiAccess() {
3189 if (mContext.checkCallingOrSelfPermission("com.android.permission.INJECT_OMADM_SETTINGS")
3190 == PackageManager.PERMISSION_GRANTED) {
3191 return;
3192 }
3193
Dianne Hackborn692a2442015-07-31 10:35:34 -07003194 unsupportedStartingFrom(VERSION_CODES.M);
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09003195 }
3196
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04003197 /**
3198 * Binds host resolutions performed by this process to {@code network}.
Paul Jensen72db88e2015-03-10 10:54:12 -04003199 * {@link #bindProcessToNetwork} takes precedence over this setting.
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04003200 *
3201 * @param network The {@link Network} to bind host resolutions from the current process to, or
3202 * {@code null} to clear the current binding.
3203 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
3204 * @hide
3205 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
3206 */
3207 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
Paul Jensenbcc76d32014-07-11 08:17:29 -04003208 return NetworkUtils.bindProcessToNetworkForHostResolution(
3209 network == null ? NETID_UNSET : network.netId);
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04003210 }
Felipe Leme1b103232016-01-22 09:44:57 -08003211
3212 /**
3213 * Device is not restricting metered network activity while application is running on
3214 * background.
3215 */
3216 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
3217
3218 /**
3219 * Device is restricting metered network activity while application is running on background,
3220 * but application is allowed to bypass it.
3221 * <p>
3222 * In this state, application should take action to mitigate metered network access.
3223 * For example, a music streaming application should switch to a low-bandwidth bitrate.
3224 */
3225 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
3226
3227 /**
3228 * Device is restricting metered network activity while application is running on background.
Felipe Leme9778f762016-01-27 14:46:39 -08003229 * <p>
Felipe Leme1b103232016-01-22 09:44:57 -08003230 * In this state, application should not try to use the network while running on background,
3231 * because it would be denied.
3232 */
3233 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
3234
Felipe Leme9778f762016-01-27 14:46:39 -08003235 /**
3236 * A change in the background metered network activity restriction has occurred.
3237 * <p>
3238 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
3239 * applies to them.
3240 * <p>
3241 * This is only sent to registered receivers, not manifest receivers.
3242 */
3243 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
3244 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
3245 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
3246
Felipe Lemeecfccea2016-01-25 11:48:04 -08003247 /** @hide */
3248 @Retention(RetentionPolicy.SOURCE)
Felipe Leme1b103232016-01-22 09:44:57 -08003249 @IntDef(flag = false, value = {
3250 RESTRICT_BACKGROUND_STATUS_DISABLED,
3251 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
3252 RESTRICT_BACKGROUND_STATUS_ENABLED,
3253 })
Felipe Leme1b103232016-01-22 09:44:57 -08003254 public @interface RestrictBackgroundStatus {
3255 }
3256
3257 private INetworkPolicyManager getNetworkPolicyManager() {
3258 synchronized (this) {
3259 if (mNPManager != null) {
3260 return mNPManager;
3261 }
3262 mNPManager = INetworkPolicyManager.Stub.asInterface(ServiceManager
3263 .getService(Context.NETWORK_POLICY_SERVICE));
3264 return mNPManager;
3265 }
3266 }
3267
3268 /**
3269 * Determines if the calling application is subject to metered network restrictions while
3270 * running on background.
3271 */
3272 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
3273 try {
3274 return getNetworkPolicyManager().getRestrictBackgroundByCaller();
3275 } catch (RemoteException e) {
3276 return RESTRICT_BACKGROUND_STATUS_DISABLED;
3277 }
3278 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003279}