blob: 0e5d049c78918c3ac04731a3dc0fc6b927e0552b [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
Felipe Leme1b103232016-01-22 09:44:57 -080018import android.annotation.IntDef;
Robin Lee244ce8e2016-01-05 18:03:46 +000019import android.annotation.Nullable;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020import android.annotation.SdkConstant;
21import android.annotation.SdkConstant.SdkConstantType;
Udam Sainib7c24872016-01-04 12:16:14 -080022import android.annotation.SystemApi;
Robert Greenwalt9258c642014-03-26 16:47:06 -070023import android.app.PendingIntent;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -070024import android.content.Context;
Robert Greenwaltd19c41c2014-05-18 23:07:25 -070025import android.content.Intent;
Lorenzo Colittiffc42b02015-07-29 11:41:21 +090026import android.content.pm.PackageManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -070027import android.os.Binder;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -070028import android.os.Build.VERSION_CODES;
Jeremy Klein36c7aa02016-01-22 14:11:45 -080029import android.os.Bundle;
Robert Greenwalt9258c642014-03-26 16:47:06 -070030import android.os.Handler;
31import android.os.HandlerThread;
Dianne Hackborn77b987f2014-02-26 16:20:52 -080032import android.os.IBinder;
33import android.os.INetworkActivityListener;
34import android.os.INetworkManagementService;
Robert Greenwalt9258c642014-03-26 16:47:06 -070035import android.os.Looper;
36import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070037import android.os.Messenger;
Lorenzo Colittiffc42b02015-07-29 11:41:21 +090038import android.os.Process;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -080040import android.os.ResultReceiver;
Dianne Hackborn77b987f2014-02-26 16:20:52 -080041import android.os.ServiceManager;
Jeff Sharkey961e3042011-08-29 16:02:57 -070042import android.provider.Settings;
Wink Saville36ffb042014-12-05 11:10:30 -080043import android.telephony.SubscriptionManager;
Dianne Hackborn77b987f2014-02-26 16:20:52 -080044import android.util.ArrayMap;
Robert Greenwalt9258c642014-03-26 16:47:06 -070045import android.util.Log;
Lorenzo Colittifcfa7d92016-03-01 22:56:37 +090046import android.util.SparseArray;
Erik Kline35bf06c2017-01-26 18:08:28 +090047import android.util.SparseIntArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048
Robert Greenwaltafa05c02014-05-21 20:04:36 -070049import com.android.internal.telephony.ITelephony;
Robert Greenwalt562cc542014-05-15 18:07:26 -070050import com.android.internal.telephony.PhoneConstants;
Lorenzo Colittifcfa7d92016-03-01 22:56:37 +090051import com.android.internal.util.MessageUtils;
Hugo Benichidafed3d2017-03-06 09:17:06 +090052import com.android.internal.util.Preconditions;
53import com.android.internal.util.Protocol;
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;
Hugo Benichidafed3d2017-03-06 09:17:06 +090060import java.util.ArrayList;
Jeremy Kleind42209d2015-12-28 15:11:58 -080061import java.util.HashMap;
Hugo Benichidafed3d2017-03-06 09:17:06 +090062import java.util.List;
63import java.util.Map;
Jeremy Kleind42209d2015-12-28 15:11:58 -080064
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065/**
66 * Class that answers queries about the state of network connectivity. It also
67 * notifies applications when network connectivity changes. Get an instance
68 * of this class by calling
69 * {@link android.content.Context#getSystemService(String) Context.getSystemService(Context.CONNECTIVITY_SERVICE)}.
70 * <p>
71 * The primary responsibilities of this class are to:
72 * <ol>
73 * <li>Monitor network connections (Wi-Fi, GPRS, UMTS, etc.)</li>
74 * <li>Send broadcast intents when network connectivity changes</li>
75 * <li>Attempt to "fail over" to another network when connectivity to a network
76 * is lost</li>
77 * <li>Provide an API that allows applications to query the coarse-grained or fine-grained
78 * state of the available networks</li>
Robert Greenwaltd19c41c2014-05-18 23:07:25 -070079 * <li>Provide an API that allows applications to request and select networks for their data
80 * traffic</li>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081 * </ol>
82 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070083public class ConnectivityManager {
84 private static final String TAG = "ConnectivityManager";
85
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086 /**
Robert Greenwaltd19c41c2014-05-18 23:07:25 -070087 * A change in network connectivity has occurred. A default connection has either
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088 * been established or lost. The NetworkInfo for the affected network is
89 * sent as an extra; it should be consulted to see what kind of
90 * connectivity event occurred.
91 * <p/>
Mark Lu33ec1062016-12-05 10:57:55 -080092 * Apps targeting Android 7.0 (API level 24) and higher do not receive this
93 * broadcast if they declare the broadcast receiver in their manifest. Apps
94 * will still receive broadcasts if they register their
95 * {@link android.content.BroadcastReceiver} with
96 * {@link android.content.Context#registerReceiver Context.registerReceiver()}
97 * and that context is still valid.
98 * <p/>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099 * If this is a connection that was the result of failing over from a
100 * disconnected network, then the FAILOVER_CONNECTION boolean extra is
101 * set to true.
102 * <p/>
103 * For a loss of connectivity, if the connectivity manager is attempting
104 * to connect (or has already connected) to another network, the
105 * NetworkInfo for the new network is also passed as an extra. This lets
106 * any receivers of the broadcast know that they should not necessarily
107 * tell the user that no data traffic will be possible. Instead, the
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800108 * receiver should expect another broadcast soon, indicating either that
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109 * the failover attempt succeeded (and so there is still overall data
110 * connectivity), or that the failover attempt failed, meaning that all
111 * connectivity has been lost.
112 * <p/>
113 * For a disconnect event, the boolean extra EXTRA_NO_CONNECTIVITY
114 * is set to {@code true} if there are no connected networks at all.
115 */
Jeff Sharkey4fa63b22013-02-20 18:21:19 -0800116 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117 public static final String CONNECTIVITY_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700118
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119 /**
Robert Greenwalte94a6ff2015-09-01 08:23:04 -0700120 * A temporary hack until SUPL system can get off the legacy APIS.
121 * They do too many network requests and the long list of apps listening
122 * and waking due to the CONNECTIVITY_ACTION bcast makes it expensive.
123 * Use this bcast intent instead for SUPL requests.
124 * @hide
125 */
126 public static final String CONNECTIVITY_ACTION_SUPL =
127 "android.net.conn.CONNECTIVITY_CHANGE_SUPL";
128
129 /**
Paul Jensen25a217c2015-02-27 22:55:47 -0500130 * The device has connected to a network that has presented a captive
131 * portal, which is blocking Internet connectivity. The user was presented
132 * with a notification that network sign in is required,
133 * and the user invoked the notification's action indicating they
Paul Jensen49e3edf2015-05-22 10:50:39 -0400134 * desire to sign in to the network. Apps handling this activity should
Paul Jensen25a217c2015-02-27 22:55:47 -0500135 * facilitate signing in to the network. This action includes a
136 * {@link Network} typed extra called {@link #EXTRA_NETWORK} that represents
137 * the network presenting the captive portal; all communication with the
138 * captive portal must be done using this {@code Network} object.
139 * <p/>
Paul Jensen49e3edf2015-05-22 10:50:39 -0400140 * This activity includes a {@link CaptivePortal} extra named
141 * {@link #EXTRA_CAPTIVE_PORTAL} that can be used to indicate different
142 * outcomes of the captive portal sign in to the system:
143 * <ul>
144 * <li> When the app handling this action believes the user has signed in to
145 * the network and the captive portal has been dismissed, the app should
146 * call {@link CaptivePortal#reportCaptivePortalDismissed} so the system can
147 * reevaluate the network. If reevaluation finds the network no longer
148 * subject to a captive portal, the network may become the default active
149 * data network. </li>
150 * <li> When the app handling this action believes the user explicitly wants
Paul Jensen25a217c2015-02-27 22:55:47 -0500151 * to ignore the captive portal and the network, the app should call
Paul Jensen49e3edf2015-05-22 10:50:39 -0400152 * {@link CaptivePortal#ignoreNetwork}. </li>
153 * </ul>
Paul Jensen25a217c2015-02-27 22:55:47 -0500154 */
155 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
156 public static final String ACTION_CAPTIVE_PORTAL_SIGN_IN = "android.net.conn.CAPTIVE_PORTAL";
157
158 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159 * The lookup key for a {@link NetworkInfo} object. Retrieve with
160 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700161 *
162 * @deprecated Since {@link NetworkInfo} can vary based on UID, applications
163 * should always obtain network information through
Paul Jensen3541e9f2015-03-18 12:23:02 -0400164 * {@link #getActiveNetworkInfo()}.
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -0700165 * @see #EXTRA_NETWORK_TYPE
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800166 */
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700167 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800168 public static final String EXTRA_NETWORK_INFO = "networkInfo";
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700169
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800170 /**
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -0700171 * Network type which triggered a {@link #CONNECTIVITY_ACTION} broadcast.
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -0700172 *
173 * @see android.content.Intent#getIntExtra(String, int)
174 */
175 public static final String EXTRA_NETWORK_TYPE = "networkType";
176
177 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800178 * The lookup key for a boolean that indicates whether a connect event
179 * is for a network to which the connectivity manager was failing over
180 * following a disconnect on another network.
181 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
182 */
183 public static final String EXTRA_IS_FAILOVER = "isFailover";
184 /**
185 * The lookup key for a {@link NetworkInfo} object. This is supplied when
186 * there is another network that it may be possible to connect to. Retrieve with
187 * {@link android.content.Intent#getParcelableExtra(String)}.
188 */
189 public static final String EXTRA_OTHER_NETWORK_INFO = "otherNetwork";
190 /**
191 * The lookup key for a boolean that indicates whether there is a
192 * complete lack of connectivity, i.e., no network is available.
193 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
194 */
195 public static final String EXTRA_NO_CONNECTIVITY = "noConnectivity";
196 /**
197 * The lookup key for a string that indicates why an attempt to connect
198 * to a network failed. The string has no particular structure. It is
199 * intended to be used in notifications presented to users. Retrieve
200 * it with {@link android.content.Intent#getStringExtra(String)}.
201 */
202 public static final String EXTRA_REASON = "reason";
203 /**
204 * The lookup key for a string that provides optionally supplied
205 * extra information about the network state. The information
206 * may be passed up from the lower networking layers, and its
207 * meaning may be specific to a particular network type. Retrieve
208 * it with {@link android.content.Intent#getStringExtra(String)}.
209 */
210 public static final String EXTRA_EXTRA_INFO = "extraInfo";
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700211 /**
212 * The lookup key for an int that provides information about
213 * our connection to the internet at large. 0 indicates no connection,
214 * 100 indicates a great connection. Retrieve it with
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700215 * {@link android.content.Intent#getIntExtra(String, int)}.
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700216 * {@hide}
217 */
218 public static final String EXTRA_INET_CONDITION = "inetCondition";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800219 /**
Paul Jensen49e3edf2015-05-22 10:50:39 -0400220 * The lookup key for a {@link CaptivePortal} object included with the
221 * {@link #ACTION_CAPTIVE_PORTAL_SIGN_IN} intent. The {@code CaptivePortal}
222 * object can be used to either indicate to the system that the captive
223 * portal has been dismissed or that the user does not want to pursue
224 * signing in to captive portal. Retrieve it with
225 * {@link android.content.Intent#getParcelableExtra(String)}.
Paul Jensen25a217c2015-02-27 22:55:47 -0500226 */
Paul Jensen49e3edf2015-05-22 10:50:39 -0400227 public static final String EXTRA_CAPTIVE_PORTAL = "android.net.extra.CAPTIVE_PORTAL";
Jan Nordqvist52eb29f2015-09-22 15:54:32 -0700228
229 /**
230 * Key for passing a URL to the captive portal login activity.
231 */
232 public static final String EXTRA_CAPTIVE_PORTAL_URL = "android.net.extra.CAPTIVE_PORTAL_URL";
233
Paul Jensen25a217c2015-02-27 22:55:47 -0500234 /**
Hugo Benichi88932752016-12-14 08:23:40 +0900235 * Key for passing a user agent string to the captive portal login activity.
236 * {@hide}
237 */
238 public static final String EXTRA_CAPTIVE_PORTAL_USER_AGENT =
239 "android.net.extra.CAPTIVE_PORTAL_USER_AGENT";
240
241 /**
Haoyu Baidb3c8672012-06-20 14:29:57 -0700242 * Broadcast action to indicate the change of data activity status
243 * (idle or active) on a network in a recent period.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800244 * The network becomes active when data transmission is started, or
245 * idle if there is no data transmission for a period of time.
Haoyu Baidb3c8672012-06-20 14:29:57 -0700246 * {@hide}
247 */
248 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
249 public static final String ACTION_DATA_ACTIVITY_CHANGE = "android.net.conn.DATA_ACTIVITY_CHANGE";
250 /**
251 * The lookup key for an enum that indicates the network device type on which this data activity
252 * change happens.
253 * {@hide}
254 */
255 public static final String EXTRA_DEVICE_TYPE = "deviceType";
256 /**
257 * The lookup key for a boolean that indicates the device is active or not. {@code true} means
258 * it is actively sending or receiving data and {@code false} means it is idle.
259 * {@hide}
260 */
261 public static final String EXTRA_IS_ACTIVE = "isActive";
Ashish Sharma0535a9f2014-03-12 18:42:23 -0700262 /**
263 * The lookup key for a long that contains the timestamp (nanos) of the radio state change.
264 * {@hide}
265 */
266 public static final String EXTRA_REALTIME_NS = "tsNanos";
Haoyu Baidb3c8672012-06-20 14:29:57 -0700267
268 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800269 * Broadcast Action: The setting for background data usage has changed
270 * values. Use {@link #getBackgroundDataSetting()} to get the current value.
271 * <p>
272 * If an application uses the network in the background, it should listen
273 * for this broadcast and stop using the background data if the value is
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700274 * {@code false}.
Jeff Sharkey54ee2ad2012-01-30 16:29:24 -0800275 * <p>
276 *
277 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability
278 * of background data depends on several combined factors, and
279 * this broadcast is no longer sent. Instead, when background
280 * data is unavailable, {@link #getActiveNetworkInfo()} will now
281 * appear disconnected. During first boot after a platform
282 * upgrade, this broadcast will be sent once if
283 * {@link #getBackgroundDataSetting()} was {@code false} before
284 * the upgrade.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800285 */
286 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Jeff Sharkey54ee2ad2012-01-30 16:29:24 -0800287 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800288 public static final String ACTION_BACKGROUND_DATA_SETTING_CHANGED =
289 "android.net.conn.BACKGROUND_DATA_SETTING_CHANGED";
290
Robert Greenwalt1e9aac22010-09-15 17:36:33 -0700291 /**
292 * Broadcast Action: The network connection may not be good
293 * uses {@code ConnectivityManager.EXTRA_INET_CONDITION} and
294 * {@code ConnectivityManager.EXTRA_NETWORK_INFO} to specify
295 * the network and it's condition.
296 * @hide
297 */
Jeff Sharkey4fa63b22013-02-20 18:21:19 -0800298 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Robert Greenwalt1e9aac22010-09-15 17:36:33 -0700299 public static final String INET_CONDITION_ACTION =
300 "android.net.conn.INET_CONDITION_ACTION";
301
Robert Greenwalt42acef32009-08-12 16:08:25 -0700302 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800303 * Broadcast Action: A tetherable connection has come or gone.
304 * Uses {@code ConnectivityManager.EXTRA_AVAILABLE_TETHER},
305 * {@code ConnectivityManager.EXTRA_ACTIVE_TETHER} and
306 * {@code ConnectivityManager.EXTRA_ERRORED_TETHER} to indicate
307 * the current state of tethering. Each include a list of
308 * interface names in that state (may be empty).
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800309 * @hide
310 */
Jeff Sharkey4fa63b22013-02-20 18:21:19 -0800311 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800312 public static final String ACTION_TETHER_STATE_CHANGED =
313 "android.net.conn.TETHER_STATE_CHANGED";
314
315 /**
316 * @hide
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800317 * gives a String[] listing all the interfaces configured for
318 * tethering and currently available for tethering.
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800319 */
Robert Greenwalt2a091d72010-02-11 18:18:40 -0800320 public static final String EXTRA_AVAILABLE_TETHER = "availableArray";
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800321
322 /**
323 * @hide
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800324 * gives a String[] listing all the interfaces currently tethered
325 * (ie, has dhcp support and packets potentially forwarded/NATed)
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800326 */
Robert Greenwalt2a091d72010-02-11 18:18:40 -0800327 public static final String EXTRA_ACTIVE_TETHER = "activeArray";
328
329 /**
330 * @hide
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800331 * gives a String[] listing all the interfaces we tried to tether and
332 * failed. Use {@link #getLastTetherError} to find the error code
333 * for any interfaces listed here.
Robert Greenwalt2a091d72010-02-11 18:18:40 -0800334 */
335 public static final String EXTRA_ERRORED_TETHER = "erroredArray";
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800336
337 /**
Russell Brenner108da0c2013-02-12 10:03:14 -0800338 * Broadcast Action: The captive portal tracker has finished its test.
339 * Sent only while running Setup Wizard, in lieu of showing a user
340 * notification.
341 * @hide
342 */
Jeff Sharkey4fa63b22013-02-20 18:21:19 -0800343 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Russell Brenner108da0c2013-02-12 10:03:14 -0800344 public static final String ACTION_CAPTIVE_PORTAL_TEST_COMPLETED =
345 "android.net.conn.CAPTIVE_PORTAL_TEST_COMPLETED";
346 /**
347 * The lookup key for a boolean that indicates whether a captive portal was detected.
348 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
349 * @hide
350 */
351 public static final String EXTRA_IS_CAPTIVE_PORTAL = "captivePortal";
352
353 /**
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900354 * Action used to display a dialog that asks the user whether to connect to a network that is
355 * not validated. This intent is used to start the dialog in settings via startActivity.
356 *
357 * @hide
358 */
359 public static final String ACTION_PROMPT_UNVALIDATED = "android.net.conn.PROMPT_UNVALIDATED";
360
361 /**
Lorenzo Colitti9be58c52016-09-15 14:02:29 +0900362 * Action used to display a dialog that asks the user whether to avoid a network that is no
363 * longer validated. This intent is used to start the dialog in settings via startActivity.
364 *
365 * @hide
366 */
367 public static final String ACTION_PROMPT_LOST_VALIDATION =
368 "android.net.conn.PROMPT_LOST_VALIDATION";
369
370 /**
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800371 * Invalid tethering type.
372 * @see #startTethering(int, OnStartTetheringCallback, boolean)
373 * @hide
374 */
375 public static final int TETHERING_INVALID = -1;
376
377 /**
378 * Wifi tethering type.
379 * @see #startTethering(int, OnStartTetheringCallback, boolean)
380 * @hide
381 */
382 @SystemApi
383 public static final int TETHERING_WIFI = 0;
384
385 /**
386 * USB tethering type.
387 * @see #startTethering(int, OnStartTetheringCallback, boolean)
388 * @hide
389 */
390 @SystemApi
391 public static final int TETHERING_USB = 1;
392
393 /**
394 * Bluetooth tethering type.
395 * @see #startTethering(int, OnStartTetheringCallback, boolean)
396 * @hide
397 */
398 @SystemApi
399 public static final int TETHERING_BLUETOOTH = 2;
400
401 /**
402 * Extra used for communicating with the TetherService. Includes the type of tethering to
403 * enable if any.
404 * @hide
405 */
406 public static final String EXTRA_ADD_TETHER_TYPE = "extraAddTetherType";
407
408 /**
409 * Extra used for communicating with the TetherService. Includes the type of tethering for
410 * which to cancel provisioning.
411 * @hide
412 */
413 public static final String EXTRA_REM_TETHER_TYPE = "extraRemTetherType";
414
415 /**
416 * Extra used for communicating with the TetherService. True to schedule a recheck of tether
417 * provisioning.
418 * @hide
419 */
420 public static final String EXTRA_SET_ALARM = "extraSetAlarm";
421
422 /**
423 * Tells the TetherService to run a provision check now.
424 * @hide
425 */
426 public static final String EXTRA_RUN_PROVISION = "extraRunProvision";
427
428 /**
429 * Extra used for communicating with the TetherService. Contains the {@link ResultReceiver}
430 * which will receive provisioning results. Can be left empty.
431 * @hide
432 */
433 public static final String EXTRA_PROVISION_CALLBACK = "extraProvisionCallback";
434
435 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800436 * The absence of a connection type.
Robert Greenwaltccf83af12011-06-02 17:30:47 -0700437 * @hide
438 */
439 public static final int TYPE_NONE = -1;
440
441 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800442 * The Mobile data connection. When active, all data traffic
443 * will use this network type's interface by default
444 * (it has a default route)
Robert Greenwalt42acef32009-08-12 16:08:25 -0700445 */
446 public static final int TYPE_MOBILE = 0;
447 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800448 * The WIFI data connection. When active, all data traffic
449 * will use this network type's interface by default
450 * (it has a default route).
Robert Greenwalt42acef32009-08-12 16:08:25 -0700451 */
452 public static final int TYPE_WIFI = 1;
453 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800454 * An MMS-specific Mobile data connection. This network type may use the
455 * same network interface as {@link #TYPE_MOBILE} or it may use a different
456 * one. This is used by applications needing to talk to the carrier's
457 * Multimedia Messaging Service servers.
Lorenzo Colittie285b432015-04-23 15:32:42 +0900458 *
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +0900459 * @deprecated Applications should instead use
460 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colittie285b432015-04-23 15:32:42 +0900461 * provides the {@link NetworkCapabilities#NET_CAPABILITY_MMS} capability.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700462 */
463 public static final int TYPE_MOBILE_MMS = 2;
464 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800465 * A SUPL-specific Mobile data connection. This network type may use the
466 * same network interface as {@link #TYPE_MOBILE} or it may use a different
467 * one. This is used by applications needing to talk to the carrier's
468 * Secure User Plane Location servers for help locating the device.
Lorenzo Colittie285b432015-04-23 15:32:42 +0900469 *
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +0900470 * @deprecated Applications should instead use
471 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colittie285b432015-04-23 15:32:42 +0900472 * provides the {@link NetworkCapabilities#NET_CAPABILITY_SUPL} capability.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700473 */
474 public static final int TYPE_MOBILE_SUPL = 3;
475 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800476 * A DUN-specific Mobile data connection. This network type may use the
477 * same network interface as {@link #TYPE_MOBILE} or it may use a different
478 * one. This is sometimes by the system when setting up an upstream connection
479 * for tethering so that the carrier is aware of DUN traffic.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700480 */
481 public static final int TYPE_MOBILE_DUN = 4;
482 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800483 * A High Priority Mobile data connection. This network type uses the
484 * same network interface as {@link #TYPE_MOBILE} but the routing setup
Lorenzo Colittie285b432015-04-23 15:32:42 +0900485 * is different.
486 *
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +0900487 * @deprecated Applications should instead use
488 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colittie285b432015-04-23 15:32:42 +0900489 * uses the {@link NetworkCapabilities#TRANSPORT_CELLULAR} transport.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700490 */
491 public static final int TYPE_MOBILE_HIPRI = 5;
jsh8214deb2010-03-11 15:04:43 -0800492 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800493 * The WiMAX data connection. When active, all data traffic
494 * will use this network type's interface by default
495 * (it has a default route).
jsh8214deb2010-03-11 15:04:43 -0800496 */
497 public static final int TYPE_WIMAX = 6;
Robert Greenwaltda3d5e62010-12-06 13:56:24 -0800498
Jaikumar Ganesh15c74392010-12-21 22:31:44 -0800499 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800500 * The Bluetooth data connection. When active, all data traffic
501 * will use this network type's interface by default
502 * (it has a default route).
Jaikumar Ganesh15c74392010-12-21 22:31:44 -0800503 */
504 public static final int TYPE_BLUETOOTH = 7;
505
Robert Greenwalt60810842011-04-22 15:28:18 -0700506 /**
507 * Dummy data connection. This should not be used on shipping devices.
508 */
Jaikumar Ganesh15c74392010-12-21 22:31:44 -0800509 public static final int TYPE_DUMMY = 8;
Wink Saville9d7d6282011-03-12 14:52:01 -0800510
Robert Greenwalt60810842011-04-22 15:28:18 -0700511 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800512 * The Ethernet data connection. When active, all data traffic
513 * will use this network type's interface by default
514 * (it has a default route).
Robert Greenwalt60810842011-04-22 15:28:18 -0700515 */
Robert Greenwalte12aec92011-01-28 14:48:37 -0800516 public static final int TYPE_ETHERNET = 9;
Robert Greenwalt60810842011-04-22 15:28:18 -0700517
Wink Saville9d7d6282011-03-12 14:52:01 -0800518 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800519 * Over the air Administration.
Wink Saville9d7d6282011-03-12 14:52:01 -0800520 * {@hide}
521 */
522 public static final int TYPE_MOBILE_FOTA = 10;
523
524 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800525 * IP Multimedia Subsystem.
Wink Saville9d7d6282011-03-12 14:52:01 -0800526 * {@hide}
527 */
528 public static final int TYPE_MOBILE_IMS = 11;
529
530 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800531 * Carrier Branded Services.
Wink Saville9d7d6282011-03-12 14:52:01 -0800532 * {@hide}
533 */
534 public static final int TYPE_MOBILE_CBS = 12;
535
repo syncaea743a2011-07-29 23:55:49 -0700536 /**
537 * A Wi-Fi p2p connection. Only requesting processes will have access to
538 * the peers connected.
539 * {@hide}
540 */
541 public static final int TYPE_WIFI_P2P = 13;
Wink Saville9d7d6282011-03-12 14:52:01 -0800542
Wink Saville5e56bc52013-07-29 15:00:57 -0700543 /**
544 * The network to use for initially attaching to the network
545 * {@hide}
546 */
547 public static final int TYPE_MOBILE_IA = 14;
repo syncaea743a2011-07-29 23:55:49 -0700548
Lorenzo Colittie285b432015-04-23 15:32:42 +0900549 /**
Robert Greenwalt4bd43892015-07-09 14:49:35 -0700550 * Emergency PDN connection for emergency services. This
551 * may include IMS and MMS in emergency situations.
Ram3e0e3bc2014-06-26 11:03:44 -0700552 * {@hide}
553 */
554 public static final int TYPE_MOBILE_EMERGENCY = 15;
555
Hui Lu1c5624a2014-01-15 11:05:36 -0500556 /**
557 * The network that uses proxy to achieve connectivity.
558 * {@hide}
559 */
560 public static final int TYPE_PROXY = 16;
Wink Saville5e56bc52013-07-29 15:00:57 -0700561
Robert Greenwalt8283f882014-07-07 17:09:01 -0700562 /**
563 * A virtual network using one or more native bearers.
564 * It may or may not be providing security services.
565 */
566 public static final int TYPE_VPN = 17;
Hui Lu1c5624a2014-01-15 11:05:36 -0500567
568 /** {@hide} */
Robert Greenwalt8283f882014-07-07 17:09:01 -0700569 public static final int MAX_RADIO_TYPE = TYPE_VPN;
570
571 /** {@hide} */
572 public static final int MAX_NETWORK_TYPE = TYPE_VPN;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800573
Jianzheng Zhoudcf03f32012-11-16 13:45:20 +0800574 /**
575 * If you want to set the default network preference,you can directly
576 * change the networkAttributes array in framework's config.xml.
577 *
578 * @deprecated Since we support so many more networks now, the single
579 * network default network preference can't really express
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800580 * the hierarchy. Instead, the default is defined by the
Jianzheng Zhoudcf03f32012-11-16 13:45:20 +0800581 * networkAttributes in config.xml. You can determine
Robert Greenwalt4c8b7482012-12-07 09:56:50 -0800582 * the current value by calling {@link #getNetworkPreference()}
Jianzheng Zhoudcf03f32012-11-16 13:45:20 +0800583 * from an App.
584 */
585 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800586 public static final int DEFAULT_NETWORK_PREFERENCE = TYPE_WIFI;
587
Jeff Sharkey625239a2012-09-26 22:03:49 -0700588 /**
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700589 * @hide
590 */
Robert Greenwalt7569f182014-06-08 16:42:59 -0700591 public final static int REQUEST_ID_UNSET = 0;
592
Paul Jensen5d59e782014-07-11 12:28:19 -0400593 /**
594 * A NetID indicating no Network is selected.
595 * Keep in sync with bionic/libc/dns/include/resolv_netid.h
596 * @hide
597 */
598 public static final int NETID_UNSET = 0;
599
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700600 private final IConnectivityManager mService;
Paul Jensene0bef712014-12-10 15:12:18 -0500601 /**
602 * A kludge to facilitate static access where a Context pointer isn't available, like in the
603 * case of the static set/getProcessDefaultNetwork methods and from the Network class.
604 * TODO: Remove this after deprecating the static methods in favor of non-static methods or
605 * methods that take a Context argument.
606 */
607 private static ConnectivityManager sInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800608
Lorenzo Colittiffc42b02015-07-29 11:41:21 +0900609 private final Context mContext;
610
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800611 private INetworkManagementService mNMService;
Felipe Leme1b103232016-01-22 09:44:57 -0800612 private INetworkPolicyManager mNPManager;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800613
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800614 /**
615 * Tests if a given integer represents a valid network type.
616 * @param networkType the type to be tested
617 * @return a boolean. {@code true} if the type is valid, else {@code false}
Paul Jensen9e59e122015-05-06 10:42:25 -0400618 * @deprecated All APIs accepting a network type are deprecated. There should be no need to
619 * validate a network type.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800620 */
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700621 public static boolean isNetworkTypeValid(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700622 return networkType >= 0 && networkType <= MAX_NETWORK_TYPE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800623 }
624
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800625 /**
626 * Returns a non-localized string representing a given network type.
627 * ONLY used for debugging output.
628 * @param type the type needing naming
629 * @return a String for the given type, or a string version of the type ("87")
630 * if no name is known.
631 * {@hide}
632 */
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700633 public static String getNetworkTypeName(int type) {
634 switch (type) {
635 case TYPE_MOBILE:
636 return "MOBILE";
637 case TYPE_WIFI:
638 return "WIFI";
639 case TYPE_MOBILE_MMS:
640 return "MOBILE_MMS";
641 case TYPE_MOBILE_SUPL:
642 return "MOBILE_SUPL";
643 case TYPE_MOBILE_DUN:
644 return "MOBILE_DUN";
645 case TYPE_MOBILE_HIPRI:
646 return "MOBILE_HIPRI";
647 case TYPE_WIMAX:
648 return "WIMAX";
649 case TYPE_BLUETOOTH:
650 return "BLUETOOTH";
651 case TYPE_DUMMY:
652 return "DUMMY";
653 case TYPE_ETHERNET:
654 return "ETHERNET";
655 case TYPE_MOBILE_FOTA:
656 return "MOBILE_FOTA";
657 case TYPE_MOBILE_IMS:
658 return "MOBILE_IMS";
659 case TYPE_MOBILE_CBS:
660 return "MOBILE_CBS";
repo syncaea743a2011-07-29 23:55:49 -0700661 case TYPE_WIFI_P2P:
662 return "WIFI_P2P";
Wink Saville5e56bc52013-07-29 15:00:57 -0700663 case TYPE_MOBILE_IA:
664 return "MOBILE_IA";
Ram3e0e3bc2014-06-26 11:03:44 -0700665 case TYPE_MOBILE_EMERGENCY:
666 return "MOBILE_EMERGENCY";
Hui Lu1c5624a2014-01-15 11:05:36 -0500667 case TYPE_PROXY:
668 return "PROXY";
Erik Kline37fbfa12014-11-19 17:23:41 +0900669 case TYPE_VPN:
670 return "VPN";
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700671 default:
672 return Integer.toString(type);
673 }
674 }
675
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800676 /**
677 * Checks if a given type uses the cellular data connection.
678 * This should be replaced in the future by a network property.
679 * @param networkType the type to check
680 * @return a boolean - {@code true} if uses cellular network, else {@code false}
681 * {@hide}
682 */
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700683 public static boolean isNetworkTypeMobile(int networkType) {
684 switch (networkType) {
685 case TYPE_MOBILE:
686 case TYPE_MOBILE_MMS:
687 case TYPE_MOBILE_SUPL:
688 case TYPE_MOBILE_DUN:
689 case TYPE_MOBILE_HIPRI:
690 case TYPE_MOBILE_FOTA:
691 case TYPE_MOBILE_IMS:
692 case TYPE_MOBILE_CBS:
Wink Saville5e56bc52013-07-29 15:00:57 -0700693 case TYPE_MOBILE_IA:
Ram3e0e3bc2014-06-26 11:03:44 -0700694 case TYPE_MOBILE_EMERGENCY:
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700695 return true;
696 default:
697 return false;
698 }
699 }
700
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800701 /**
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700702 * Checks if the given network type is backed by a Wi-Fi radio.
703 *
704 * @hide
705 */
706 public static boolean isNetworkTypeWifi(int networkType) {
707 switch (networkType) {
708 case TYPE_WIFI:
709 case TYPE_WIFI_P2P:
710 return true;
711 default:
712 return false;
713 }
714 }
715
716 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800717 * Specifies the preferred network type. When the device has more
718 * than one type available the preferred network type will be used.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800719 *
720 * @param preference the network type to prefer over all others. It is
721 * unspecified what happens to the old preferred network in the
722 * overall ordering.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -0700723 * @deprecated Functionality has been removed as it no longer makes sense,
724 * with many more than two networks - we'd need an array to express
725 * preference. Instead we use dynamic network properties of
726 * the networks to describe their precedence.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800727 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800728 public void setNetworkPreference(int preference) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800729 }
730
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800731 /**
732 * Retrieves the current preferred network type.
Paul Jensenb2748922015-05-06 11:10:18 -0400733 * <p>This method requires the caller to hold the permission
734 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800735 *
736 * @return an integer representing the preferred network type
737 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -0700738 * @deprecated Functionality has been removed as it no longer makes sense,
739 * with many more than two networks - we'd need an array to express
740 * preference. Instead we use dynamic network properties of
741 * the networks to describe their precedence.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800742 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800743 public int getNetworkPreference() {
Robert Greenwaltd19c41c2014-05-18 23:07:25 -0700744 return TYPE_NONE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800745 }
746
Scott Main671644c2011-10-06 19:02:28 -0700747 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800748 * Returns details about the currently active default data network. When
749 * connected, this network is the default route for outgoing connections.
750 * You should always check {@link NetworkInfo#isConnected()} before initiating
751 * network traffic. This may return {@code null} when there is no default
752 * network.
Paul Jensenb2748922015-05-06 11:10:18 -0400753 * <p>This method requires the caller to hold the permission
754 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800755 *
756 * @return a {@link NetworkInfo} object for the current default network
Paul Jensen0d719ca2015-02-13 14:18:39 -0500757 * or {@code null} if no default network is currently active
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -0700758 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800759 public NetworkInfo getActiveNetworkInfo() {
760 try {
761 return mService.getActiveNetworkInfo();
762 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -0700763 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800764 }
765 }
766
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800767 /**
Paul Jensen31a94f42015-02-13 14:18:39 -0500768 * Returns a {@link Network} object corresponding to the currently active
769 * default data network. In the event that the current active default data
770 * network disconnects, the returned {@code Network} object will no longer
771 * be usable. This will return {@code null} when there is no default
772 * network.
Paul Jensenb2748922015-05-06 11:10:18 -0400773 * <p>This method requires the caller to hold the permission
774 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Paul Jensen31a94f42015-02-13 14:18:39 -0500775 *
776 * @return a {@link Network} object for the current default network or
777 * {@code null} if no default network is currently active
Paul Jensen31a94f42015-02-13 14:18:39 -0500778 */
779 public Network getActiveNetwork() {
780 try {
781 return mService.getActiveNetwork();
782 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -0700783 throw e.rethrowFromSystemServer();
Paul Jensen31a94f42015-02-13 14:18:39 -0500784 }
785 }
786
787 /**
Robin Leed2baf792016-03-24 12:07:00 +0000788 * Returns a {@link Network} object corresponding to the currently active
789 * default data network for a specific UID. In the event that the default data
790 * network disconnects, the returned {@code Network} object will no longer
791 * be usable. This will return {@code null} when there is no default
792 * network for the UID.
793 * <p>This method requires the caller to hold the permission
794 * {@link android.Manifest.permission#CONNECTIVITY_INTERNAL}.
795 *
796 * @return a {@link Network} object for the current default network for the
797 * given UID or {@code null} if no default network is currently active
798 *
799 * @hide
800 */
801 public Network getActiveNetworkForUid(int uid) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600802 return getActiveNetworkForUid(uid, false);
803 }
804
805 /** {@hide} */
806 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +0000807 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600808 return mService.getActiveNetworkForUid(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +0000809 } catch (RemoteException e) {
810 throw e.rethrowFromSystemServer();
811 }
812 }
813
814 /**
Robin Lee244ce8e2016-01-05 18:03:46 +0000815 * Configures an always-on VPN connection through a specific application.
816 * This connection is automatically granted and persisted after a reboot.
817 *
818 * <p>The designated package should declare a {@link VpnService} in its
819 * manifest guarded by {@link android.Manifest.permission.BIND_VPN_SERVICE},
820 * otherwise the call will fail.
821 *
822 * @param userId The identifier of the user to set an always-on VPN for.
823 * @param vpnPackage The package name for an installed VPN app on the device, or {@code null}
824 * to remove an existing always-on VPN configuration.
Robin Leedc679712016-05-03 13:23:03 +0100825 * @param lockdownEnabled {@code true} to disallow networking when the VPN is not connected or
826 * {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +0000827 * @return {@code true} if the package is set as always-on VPN controller;
828 * {@code false} otherwise.
829 * @hide
830 */
Robin Leedc679712016-05-03 13:23:03 +0100831 public boolean setAlwaysOnVpnPackageForUser(int userId, @Nullable String vpnPackage,
832 boolean lockdownEnabled) {
Robin Lee244ce8e2016-01-05 18:03:46 +0000833 try {
Robin Leedc679712016-05-03 13:23:03 +0100834 return mService.setAlwaysOnVpnPackage(userId, vpnPackage, lockdownEnabled);
Robin Lee244ce8e2016-01-05 18:03:46 +0000835 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -0700836 throw e.rethrowFromSystemServer();
Robin Lee244ce8e2016-01-05 18:03:46 +0000837 }
838 }
839
840 /**
841 * Returns the package name of the currently set always-on VPN application.
842 * If there is no always-on VPN set, or the VPN is provided by the system instead
843 * of by an app, {@code null} will be returned.
844 *
845 * @return Package name of VPN controller responsible for always-on VPN,
846 * or {@code null} if none is set.
847 * @hide
848 */
849 public String getAlwaysOnVpnPackageForUser(int userId) {
850 try {
851 return mService.getAlwaysOnVpnPackage(userId);
852 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -0700853 throw e.rethrowFromSystemServer();
Robin Lee244ce8e2016-01-05 18:03:46 +0000854 }
855 }
856
857 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800858 * Returns details about the currently active default data network
859 * for a given uid. This is for internal use only to avoid spying
860 * other apps.
Paul Jensenb2748922015-05-06 11:10:18 -0400861 * <p>This method requires the caller to hold the permission
862 * {@link android.Manifest.permission#CONNECTIVITY_INTERNAL}
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800863 *
864 * @return a {@link NetworkInfo} object for the current default network
865 * for the given uid or {@code null} if no default network is
866 * available for the specified uid.
867 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800868 * {@hide}
869 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700870 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600871 return getActiveNetworkInfoForUid(uid, false);
872 }
873
874 /** {@hide} */
875 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700876 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600877 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700878 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -0700879 throw e.rethrowFromSystemServer();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700880 }
881 }
882
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800883 /**
884 * Returns connection status information about a particular
885 * network type.
Paul Jensenb2748922015-05-06 11:10:18 -0400886 * <p>This method requires the caller to hold the permission
887 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800888 *
889 * @param networkType integer specifying which networkType in
890 * which you're interested.
891 * @return a {@link NetworkInfo} object for the requested
892 * network type or {@code null} if the type is not
893 * supported by the device.
894 *
Paul Jensen3541e9f2015-03-18 12:23:02 -0400895 * @deprecated This method does not support multiple connected networks
896 * of the same type. Use {@link #getAllNetworks} and
897 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800898 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800899 public NetworkInfo getNetworkInfo(int networkType) {
900 try {
901 return mService.getNetworkInfo(networkType);
902 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -0700903 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800904 }
905 }
906
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800907 /**
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -0700908 * Returns connection status information about a particular
909 * Network.
Paul Jensenb2748922015-05-06 11:10:18 -0400910 * <p>This method requires the caller to hold the permission
911 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -0700912 *
913 * @param network {@link Network} specifying which network
914 * in which you're interested.
915 * @return a {@link NetworkInfo} object for the requested
916 * network or {@code null} if the {@code Network}
917 * is not valid.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -0700918 */
919 public NetworkInfo getNetworkInfo(Network network) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600920 return getNetworkInfoForUid(network, Process.myUid(), false);
921 }
922
923 /** {@hide} */
924 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -0700925 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600926 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -0700927 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -0700928 throw e.rethrowFromSystemServer();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -0700929 }
930 }
931
932 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800933 * Returns connection status information about all network
934 * types supported by the device.
Paul Jensenb2748922015-05-06 11:10:18 -0400935 * <p>This method requires the caller to hold the permission
936 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800937 *
938 * @return an array of {@link NetworkInfo} objects. Check each
939 * {@link NetworkInfo#getType} for which type each applies.
940 *
Paul Jensen3541e9f2015-03-18 12:23:02 -0400941 * @deprecated This method does not support multiple connected networks
942 * of the same type. Use {@link #getAllNetworks} and
943 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800944 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800945 public NetworkInfo[] getAllNetworkInfo() {
946 try {
947 return mService.getAllNetworkInfo();
948 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -0700949 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800950 }
951 }
952
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800953 /**
Lorenzo Colittib57edc52014-08-22 17:10:50 -0700954 * Returns the {@link Network} object currently serving a given type, or
955 * null if the given type is not connected.
956 *
957 * <p>This method requires the caller to hold the permission
958 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
959 *
960 * @hide
Paul Jensen3541e9f2015-03-18 12:23:02 -0400961 * @deprecated This method does not support multiple connected networks
962 * of the same type. Use {@link #getAllNetworks} and
963 * {@link #getNetworkInfo(android.net.Network)} instead.
Lorenzo Colittib57edc52014-08-22 17:10:50 -0700964 */
965 public Network getNetworkForType(int networkType) {
966 try {
967 return mService.getNetworkForType(networkType);
968 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -0700969 throw e.rethrowFromSystemServer();
Lorenzo Colittib57edc52014-08-22 17:10:50 -0700970 }
971 }
972
973 /**
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -0700974 * Returns an array of all {@link Network} currently tracked by the
975 * framework.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -0700976 * <p>This method requires the caller to hold the permission
977 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Paul Jensenb2748922015-05-06 11:10:18 -0400978 *
979 * @return an array of {@link Network} objects.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -0700980 */
981 public Network[] getAllNetworks() {
982 try {
983 return mService.getAllNetworks();
984 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -0700985 throw e.rethrowFromSystemServer();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -0700986 }
987 }
988
989 /**
Lorenzo Colittie285b432015-04-23 15:32:42 +0900990 * Returns an array of {@link android.net.NetworkCapabilities} objects, representing
Lorenzo Colitti403aa262014-11-28 11:21:30 +0900991 * the Networks that applications run by the given user will use by default.
992 * @hide
993 */
994 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
995 try {
996 return mService.getDefaultNetworkCapabilitiesForUser(userId);
997 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -0700998 throw e.rethrowFromSystemServer();
Lorenzo Colitti403aa262014-11-28 11:21:30 +0900999 }
1000 }
1001
1002 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001003 * Returns the IP information for the current default network.
Paul Jensenb2748922015-05-06 11:10:18 -04001004 * <p>This method requires the caller to hold the permission
1005 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001006 *
1007 * @return a {@link LinkProperties} object describing the IP info
1008 * for the current default network, or {@code null} if there
1009 * is no current default network.
1010 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001011 * {@hide}
1012 */
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001013 public LinkProperties getActiveLinkProperties() {
1014 try {
1015 return mService.getActiveLinkProperties();
1016 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001017 throw e.rethrowFromSystemServer();
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001018 }
1019 }
1020
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001021 /**
1022 * Returns the IP information for a given network type.
Paul Jensenb2748922015-05-06 11:10:18 -04001023 * <p>This method requires the caller to hold the permission
1024 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001025 *
1026 * @param networkType the network type of interest.
1027 * @return a {@link LinkProperties} object describing the IP info
1028 * for the given networkType, or {@code null} if there is
1029 * no current default network.
1030 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001031 * {@hide}
Paul Jensen3541e9f2015-03-18 12:23:02 -04001032 * @deprecated This method does not support multiple connected networks
1033 * of the same type. Use {@link #getAllNetworks},
1034 * {@link #getNetworkInfo(android.net.Network)}, and
1035 * {@link #getLinkProperties(android.net.Network)} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001036 */
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001037 public LinkProperties getLinkProperties(int networkType) {
1038 try {
Robert Greenwalt9258c642014-03-26 16:47:06 -07001039 return mService.getLinkPropertiesForType(networkType);
1040 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001041 throw e.rethrowFromSystemServer();
Robert Greenwalt9258c642014-03-26 16:47:06 -07001042 }
1043 }
1044
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001045 /**
1046 * Get the {@link LinkProperties} for the given {@link Network}. This
1047 * will return {@code null} if the network is unknown.
Paul Jensenb2748922015-05-06 11:10:18 -04001048 * <p>This method requires the caller to hold the permission
1049 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001050 *
1051 * @param network The {@link Network} object identifying the network in question.
1052 * @return The {@link LinkProperties} for the network, or {@code null}.
Paul Jensenb2748922015-05-06 11:10:18 -04001053 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07001054 public LinkProperties getLinkProperties(Network network) {
1055 try {
1056 return mService.getLinkProperties(network);
1057 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001058 throw e.rethrowFromSystemServer();
Robert Greenwalt9258c642014-03-26 16:47:06 -07001059 }
1060 }
1061
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001062 /**
Lorenzo Colittie285b432015-04-23 15:32:42 +09001063 * Get the {@link android.net.NetworkCapabilities} for the given {@link Network}. This
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001064 * will return {@code null} if the network is unknown.
Paul Jensenb2748922015-05-06 11:10:18 -04001065 * <p>This method requires the caller to hold the permission
1066 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001067 *
1068 * @param network The {@link Network} object identifying the network in question.
Lorenzo Colittie285b432015-04-23 15:32:42 +09001069 * @return The {@link android.net.NetworkCapabilities} for the network, or {@code null}.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001070 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07001071 public NetworkCapabilities getNetworkCapabilities(Network network) {
1072 try {
1073 return mService.getNetworkCapabilities(network);
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001074 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001075 throw e.rethrowFromSystemServer();
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001076 }
1077 }
1078
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001079 /**
Udam Sainib7c24872016-01-04 12:16:14 -08001080 * Gets the URL that should be used for resolving whether a captive portal is present.
1081 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1082 * portal is present.
1083 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1084 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1085 *
1086 * @hide
1087 */
1088 @SystemApi
1089 public String getCaptivePortalServerUrl() {
1090 try {
1091 return mService.getCaptivePortalServerUrl();
1092 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001093 throw e.rethrowFromSystemServer();
Udam Sainib7c24872016-01-04 12:16:14 -08001094 }
1095 }
1096
1097 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001098 * Tells the underlying networking system that the caller wants to
1099 * begin using the named feature. The interpretation of {@code feature}
1100 * is completely up to each networking implementation.
Lorenzo Colittid5427052015-10-15 16:29:00 +09001101 *
1102 * <p>This method requires the caller to hold either the
1103 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1104 * or the ability to modify system settings as determined by
1105 * {@link android.provider.Settings.System#canWrite}.</p>
1106 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001107 * @param networkType specifies which network the request pertains to
1108 * @param feature the name of the feature to be used
1109 * @return an integer value representing the outcome of the request.
1110 * The interpretation of this value is specific to each networking
1111 * implementation+feature combination, except that the value {@code -1}
1112 * always indicates failure.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001113 *
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +09001114 * @deprecated Deprecated in favor of the cleaner
1115 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
Dianne Hackborn692a2442015-07-31 10:35:34 -07001116 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001117 * throw {@code UnsupportedOperationException} if called.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001118 */
1119 public int startUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001120 checkLegacyRoutingApiAccess();
Robert Greenwalt562cc542014-05-15 18:07:26 -07001121 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1122 if (netCap == null) {
1123 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1124 feature);
1125 return PhoneConstants.APN_REQUEST_FAILED;
1126 }
1127
1128 NetworkRequest request = null;
1129 synchronized (sLegacyRequests) {
1130 LegacyRequest l = sLegacyRequests.get(netCap);
1131 if (l != null) {
1132 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1133 renewRequestLocked(l);
1134 if (l.currentNetwork != null) {
1135 return PhoneConstants.APN_ALREADY_ACTIVE;
1136 } else {
1137 return PhoneConstants.APN_REQUEST_STARTED;
1138 }
1139 }
1140
1141 request = requestNetworkForFeatureLocked(netCap);
1142 }
1143 if (request != null) {
Robert Greenwalt257ee5f2014-06-20 10:58:45 -07001144 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001145 return PhoneConstants.APN_REQUEST_STARTED;
1146 } else {
1147 Log.d(TAG, " request Failed");
1148 return PhoneConstants.APN_REQUEST_FAILED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001149 }
1150 }
1151
1152 /**
1153 * Tells the underlying networking system that the caller is finished
1154 * using the named feature. The interpretation of {@code feature}
1155 * is completely up to each networking implementation.
Lorenzo Colittid5427052015-10-15 16:29:00 +09001156 *
1157 * <p>This method requires the caller to hold either the
1158 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1159 * or the ability to modify system settings as determined by
1160 * {@link android.provider.Settings.System#canWrite}.</p>
1161 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001162 * @param networkType specifies which network the request pertains to
1163 * @param feature the name of the feature that is no longer needed
1164 * @return an integer value representing the outcome of the request.
1165 * The interpretation of this value is specific to each networking
1166 * implementation+feature combination, except that the value {@code -1}
1167 * always indicates failure.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001168 *
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09001169 * @deprecated Deprecated in favor of the cleaner
1170 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
Dianne Hackborn692a2442015-07-31 10:35:34 -07001171 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001172 * throw {@code UnsupportedOperationException} if called.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001173 */
1174 public int stopUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001175 checkLegacyRoutingApiAccess();
Robert Greenwalt562cc542014-05-15 18:07:26 -07001176 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1177 if (netCap == null) {
1178 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
1179 feature);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001180 return -1;
1181 }
Robert Greenwalt562cc542014-05-15 18:07:26 -07001182
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001183 if (removeRequestForFeature(netCap)) {
Robert Greenwalt562cc542014-05-15 18:07:26 -07001184 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001185 }
1186 return 1;
1187 }
1188
1189 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
1190 if (networkType == TYPE_MOBILE) {
Erik Kline35bf06c2017-01-26 18:08:28 +09001191 switch (feature) {
1192 case "enableCBS":
1193 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
1194 case "enableDUN":
1195 case "enableDUNAlways":
1196 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
1197 case "enableFOTA":
1198 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
1199 case "enableHIPRI":
1200 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
1201 case "enableIMS":
1202 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
1203 case "enableMMS":
1204 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
1205 case "enableSUPL":
1206 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
1207 default:
1208 return null;
Robert Greenwalt562cc542014-05-15 18:07:26 -07001209 }
Erik Kline35bf06c2017-01-26 18:08:28 +09001210 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
1211 return networkCapabilitiesForType(TYPE_WIFI_P2P);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001212 }
1213 return null;
1214 }
1215
Robert Greenwalt06314e42014-10-29 14:04:06 -07001216 /**
1217 * Guess what the network request was trying to say so that the resulting
1218 * network is accessible via the legacy (deprecated) API such as
1219 * requestRouteToHost.
Lorenzo Colittidef4cb02015-11-25 20:28:50 +09001220 *
1221 * This means we should try to be fairly precise about transport and
Robert Greenwalt06314e42014-10-29 14:04:06 -07001222 * capability but ignore things such as networkSpecifier.
1223 * If the request has more than one transport or capability it doesn't
1224 * match the old legacy requests (they selected only single transport/capability)
1225 * so this function cannot map the request to a single legacy type and
1226 * the resulting network will not be available to the legacy APIs.
1227 *
Lorenzo Colittidef4cb02015-11-25 20:28:50 +09001228 * This code is only called from the requestNetwork API (L and above).
1229 *
1230 * Setting a legacy type causes CONNECTIVITY_ACTION broadcasts, which are expensive
1231 * because they wake up lots of apps - see http://b/23350688 . So we currently only
1232 * do this for SUPL requests, which are the only ones that we know need it. If
1233 * omitting these broadcasts causes unacceptable app breakage, then for backwards
1234 * compatibility we can send them:
1235 *
1236 * if (targetSdkVersion < Build.VERSION_CODES.M) && // legacy API unsupported >= M
1237 * targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP)) // requestNetwork not present < L
1238 *
Robert Greenwalt06314e42014-10-29 14:04:06 -07001239 * TODO - This should be removed when the legacy APIs are removed.
1240 */
Ye Wenb87875e2014-07-21 14:19:01 -07001241 private int inferLegacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
1242 if (netCap == null) {
1243 return TYPE_NONE;
1244 }
Robert Greenwalt06314e42014-10-29 14:04:06 -07001245
Ye Wenb87875e2014-07-21 14:19:01 -07001246 if (!netCap.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
1247 return TYPE_NONE;
1248 }
Robert Greenwalt06314e42014-10-29 14:04:06 -07001249
Lifu Tang30f95a72016-01-07 23:20:38 -08001250 // Do this only for SUPL, until GnssLocationProvider is fixed. http://b/25876485 .
Lorenzo Colittidef4cb02015-11-25 20:28:50 +09001251 if (!netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1252 // NOTE: if this causes app breakage, we should not just comment out this early return;
1253 // instead, we should make this early return conditional on the requesting app's target
1254 // SDK version, as described in the comment above.
1255 return TYPE_NONE;
1256 }
1257
Robert Greenwalt06314e42014-10-29 14:04:06 -07001258 String type = null;
1259 int result = TYPE_NONE;
1260
Ye Wenb87875e2014-07-21 14:19:01 -07001261 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
Robert Greenwalt06314e42014-10-29 14:04:06 -07001262 type = "enableCBS";
1263 result = TYPE_MOBILE_CBS;
1264 } else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1265 type = "enableIMS";
1266 result = TYPE_MOBILE_IMS;
1267 } else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1268 type = "enableFOTA";
1269 result = TYPE_MOBILE_FOTA;
1270 } else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1271 type = "enableDUN";
1272 result = TYPE_MOBILE_DUN;
1273 } else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
Lorenzo Colittidef4cb02015-11-25 20:28:50 +09001274 type = "enableSUPL";
Robert Greenwalt06314e42014-10-29 14:04:06 -07001275 result = TYPE_MOBILE_SUPL;
Robert Greenwalt74ab4fa2015-08-28 12:37:54 -07001276 // back out this hack for mms as they no longer need this and it's causing
1277 // device slowdowns - b/23350688 (note, supl still needs this)
1278 //} else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1279 // type = "enableMMS";
1280 // result = TYPE_MOBILE_MMS;
Robert Greenwalt06314e42014-10-29 14:04:06 -07001281 } else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1282 type = "enableHIPRI";
1283 result = TYPE_MOBILE_HIPRI;
Ye Wenb87875e2014-07-21 14:19:01 -07001284 }
Robert Greenwalt06314e42014-10-29 14:04:06 -07001285 if (type != null) {
1286 NetworkCapabilities testCap = networkCapabilitiesForFeature(TYPE_MOBILE, type);
1287 if (testCap.equalsNetCapabilities(netCap) && testCap.equalsTransportTypes(netCap)) {
1288 return result;
Ye Wenb87875e2014-07-21 14:19:01 -07001289 }
1290 }
1291 return TYPE_NONE;
1292 }
1293
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07001294 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
Robert Greenwalt562cc542014-05-15 18:07:26 -07001295 if (netCap == null) return TYPE_NONE;
1296 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
1297 return TYPE_MOBILE_CBS;
1298 }
1299 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1300 return TYPE_MOBILE_IMS;
1301 }
1302 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1303 return TYPE_MOBILE_FOTA;
1304 }
1305 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1306 return TYPE_MOBILE_DUN;
1307 }
1308 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1309 return TYPE_MOBILE_SUPL;
1310 }
1311 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1312 return TYPE_MOBILE_MMS;
1313 }
1314 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1315 return TYPE_MOBILE_HIPRI;
1316 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07001317 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
1318 return TYPE_WIFI_P2P;
1319 }
Robert Greenwalt562cc542014-05-15 18:07:26 -07001320 return TYPE_NONE;
1321 }
1322
1323 private static class LegacyRequest {
1324 NetworkCapabilities networkCapabilities;
1325 NetworkRequest networkRequest;
1326 int expireSequenceNumber;
1327 Network currentNetwork;
1328 int delay = -1;
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001329
1330 private void clearDnsBinding() {
1331 if (currentNetwork != null) {
1332 currentNetwork = null;
1333 setProcessDefaultNetworkForHostResolution(null);
1334 }
1335 }
1336
Robert Greenwalt6078b502014-06-11 16:05:07 -07001337 NetworkCallback networkCallback = new NetworkCallback() {
Robert Greenwalt562cc542014-05-15 18:07:26 -07001338 @Override
Robert Greenwalt6078b502014-06-11 16:05:07 -07001339 public void onAvailable(Network network) {
Robert Greenwalt562cc542014-05-15 18:07:26 -07001340 currentNetwork = network;
1341 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04001342 setProcessDefaultNetworkForHostResolution(network);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001343 }
1344 @Override
Robert Greenwalt6078b502014-06-11 16:05:07 -07001345 public void onLost(Network network) {
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001346 if (network.equals(currentNetwork)) clearDnsBinding();
Robert Greenwalt562cc542014-05-15 18:07:26 -07001347 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
1348 }
1349 };
1350 }
1351
Robert Greenwaltfab501672014-07-23 11:44:01 -07001352 private static HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
Robert Greenwalt562cc542014-05-15 18:07:26 -07001353 new HashMap<NetworkCapabilities, LegacyRequest>();
1354
1355 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
1356 synchronized (sLegacyRequests) {
1357 LegacyRequest l = sLegacyRequests.get(netCap);
1358 if (l != null) return l.networkRequest;
1359 }
1360 return null;
1361 }
1362
1363 private void renewRequestLocked(LegacyRequest l) {
1364 l.expireSequenceNumber++;
1365 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
1366 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
1367 }
1368
1369 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
1370 int ourSeqNum = -1;
1371 synchronized (sLegacyRequests) {
1372 LegacyRequest l = sLegacyRequests.get(netCap);
1373 if (l == null) return;
1374 ourSeqNum = l.expireSequenceNumber;
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001375 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001376 }
1377 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
1378 }
1379
1380 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
1381 int delay = -1;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07001382 int type = legacyTypeForNetworkCapabilities(netCap);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001383 try {
1384 delay = mService.getRestoreDefaultNetworkDelay(type);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001385 } catch (RemoteException e) {
1386 throw e.rethrowFromSystemServer();
1387 }
Robert Greenwalt562cc542014-05-15 18:07:26 -07001388 LegacyRequest l = new LegacyRequest();
1389 l.networkCapabilities = netCap;
1390 l.delay = delay;
1391 l.expireSequenceNumber = 0;
Hugo Benichi2583ef02017-02-02 17:02:36 +09001392 l.networkRequest = sendRequestForNetwork(
1393 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
Robert Greenwalt562cc542014-05-15 18:07:26 -07001394 if (l.networkRequest == null) return null;
1395 sLegacyRequests.put(netCap, l);
1396 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
1397 return l.networkRequest;
1398 }
1399
1400 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
1401 if (delay >= 0) {
1402 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
Hugo Benichi2583ef02017-02-02 17:02:36 +09001403 CallbackHandler handler = getDefaultHandler();
Hugo Benichi6f260f32017-02-03 14:18:44 +09001404 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
1405 handler.sendMessageDelayed(msg, delay);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001406 }
1407 }
1408
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001409 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
1410 final LegacyRequest l;
Robert Greenwalt562cc542014-05-15 18:07:26 -07001411 synchronized (sLegacyRequests) {
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001412 l = sLegacyRequests.remove(netCap);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001413 }
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001414 if (l == null) return false;
1415 unregisterNetworkCallback(l.networkCallback);
1416 l.clearDnsBinding();
1417 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001418 }
1419
Erik Kline35bf06c2017-01-26 18:08:28 +09001420 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
1421 static {
1422 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
1423 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
1424 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
1425 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
1426 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
1427 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1428 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1429 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
1430 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
1431 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
1432 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
1433 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
1434 }
1435
1436 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
1437 static {
1438 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
1439 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
1440 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
1441 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
1442 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
1443 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
1444 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
1445 }
1446
1447 /**
1448 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
1449 * instance suitable for registering a request or callback. Throws an
1450 * IllegalArgumentException if no mapping from the legacy type to
1451 * NetworkCapabilities is known.
1452 *
1453 * @hide
1454 */
1455 public static NetworkCapabilities networkCapabilitiesForType(int type) {
1456 final NetworkCapabilities nc = new NetworkCapabilities();
1457
1458 // Map from type to transports.
1459 final int NOT_FOUND = -1;
1460 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
1461 if (transport == NOT_FOUND) {
1462 throw new IllegalArgumentException("unknown legacy type: " + type);
1463 }
1464 nc.addTransportType(transport);
1465
1466 // Map from type to capabilities.
1467 nc.addCapability(sLegacyTypeToCapability.get(
1468 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
1469 nc.maybeMarkCapabilitiesRestricted();
1470 return nc;
1471 }
1472
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001473 /** @hide */
1474 public static class PacketKeepaliveCallback {
1475 /** The requested keepalive was successfully started. */
1476 public void onStarted() {}
1477 /** The keepalive was successfully stopped. */
1478 public void onStopped() {}
1479 /** An error occurred. */
1480 public void onError(int error) {}
1481 }
1482
1483 /**
1484 * Allows applications to request that the system periodically send specific packets on their
1485 * behalf, using hardware offload to save battery power.
1486 *
1487 * To request that the system send keepalives, call one of the methods that return a
1488 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
1489 * passing in a non-null callback. If the callback is successfully started, the callback's
1490 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
1491 * specifying one of the {@code ERROR_*} constants in this class.
1492 *
1493 * To stop an existing keepalive, call {@link stop}. The system will call {@code onStopped} if
1494 * the operation was successfull or {@code onError} if an error occurred.
1495 *
1496 * @hide
1497 */
1498 public class PacketKeepalive {
1499
1500 private static final String TAG = "PacketKeepalive";
1501
1502 /** @hide */
1503 public static final int SUCCESS = 0;
1504
1505 /** @hide */
1506 public static final int NO_KEEPALIVE = -1;
1507
1508 /** @hide */
1509 public static final int BINDER_DIED = -10;
1510
1511 /** The specified {@code Network} is not connected. */
1512 public static final int ERROR_INVALID_NETWORK = -20;
1513 /** The specified IP addresses are invalid. For example, the specified source IP address is
1514 * not configured on the specified {@code Network}. */
1515 public static final int ERROR_INVALID_IP_ADDRESS = -21;
1516 /** The requested port is invalid. */
1517 public static final int ERROR_INVALID_PORT = -22;
1518 /** The packet length is invalid (e.g., too long). */
1519 public static final int ERROR_INVALID_LENGTH = -23;
1520 /** The packet transmission interval is invalid (e.g., too short). */
1521 public static final int ERROR_INVALID_INTERVAL = -24;
1522
1523 /** The hardware does not support this request. */
1524 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
Lorenzo Colitti9d1284e2015-09-08 16:46:36 +09001525 /** The hardware returned an error. */
1526 public static final int ERROR_HARDWARE_ERROR = -31;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001527
1528 public static final int NATT_PORT = 4500;
1529
1530 private final Network mNetwork;
1531 private final PacketKeepaliveCallback mCallback;
1532 private final Looper mLooper;
1533 private final Messenger mMessenger;
1534
1535 private volatile Integer mSlot;
1536
1537 void stopLooper() {
1538 mLooper.quit();
1539 }
1540
1541 public void stop() {
1542 try {
1543 mService.stopKeepalive(mNetwork, mSlot);
1544 } catch (RemoteException e) {
1545 Log.e(TAG, "Error stopping packet keepalive: ", e);
1546 stopLooper();
1547 }
1548 }
1549
1550 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09001551 Preconditions.checkNotNull(network, "network cannot be null");
1552 Preconditions.checkNotNull(callback, "callback cannot be null");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001553 mNetwork = network;
1554 mCallback = callback;
1555 HandlerThread thread = new HandlerThread(TAG);
1556 thread.start();
1557 mLooper = thread.getLooper();
1558 mMessenger = new Messenger(new Handler(mLooper) {
1559 @Override
1560 public void handleMessage(Message message) {
1561 switch (message.what) {
1562 case NetworkAgent.EVENT_PACKET_KEEPALIVE:
1563 int error = message.arg2;
1564 try {
1565 if (error == SUCCESS) {
1566 if (mSlot == null) {
1567 mSlot = message.arg1;
1568 mCallback.onStarted();
1569 } else {
1570 mSlot = null;
1571 stopLooper();
1572 mCallback.onStopped();
1573 }
1574 } else {
1575 stopLooper();
1576 mCallback.onError(error);
1577 }
1578 } catch (Exception e) {
1579 Log.e(TAG, "Exception in keepalive callback(" + error + ")", e);
1580 }
1581 break;
1582 default:
1583 Log.e(TAG, "Unhandled message " + Integer.toHexString(message.what));
1584 break;
1585 }
1586 }
1587 });
1588 }
1589 }
1590
1591 /**
1592 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
1593 *
1594 * @hide
1595 */
1596 public PacketKeepalive startNattKeepalive(
1597 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
1598 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
1599 final PacketKeepalive k = new PacketKeepalive(network, callback);
1600 try {
1601 mService.startNattKeepalive(network, intervalSeconds, k.mMessenger, new Binder(),
1602 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
1603 } catch (RemoteException e) {
1604 Log.e(TAG, "Error starting packet keepalive: ", e);
1605 k.stopLooper();
1606 return null;
1607 }
1608 return k;
1609 }
1610
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001611 /**
1612 * Ensure that a network route exists to deliver traffic to the specified
1613 * host via the specified network interface. An attempt to add a route that
1614 * already exists is ignored, but treated as successful.
Lorenzo Colittid5427052015-10-15 16:29:00 +09001615 *
1616 * <p>This method requires the caller to hold either the
1617 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1618 * or the ability to modify system settings as determined by
1619 * {@link android.provider.Settings.System#canWrite}.</p>
1620 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001621 * @param networkType the type of the network over which traffic to the specified
1622 * host is to be routed
1623 * @param hostAddress the IP address of the host to which the route is desired
1624 * @return {@code true} on success, {@code false} on failure
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001625 *
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +09001626 * @deprecated Deprecated in favor of the
1627 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
1628 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
Dianne Hackborn692a2442015-07-31 10:35:34 -07001629 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001630 * throw {@code UnsupportedOperationException} if called.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001631 */
1632 public boolean requestRouteToHost(int networkType, int hostAddress) {
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001633 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001634 }
1635
1636 /**
1637 * Ensure that a network route exists to deliver traffic to the specified
1638 * host via the specified network interface. An attempt to add a route that
1639 * already exists is ignored, but treated as successful.
Lorenzo Colittid5427052015-10-15 16:29:00 +09001640 *
1641 * <p>This method requires the caller to hold either the
1642 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1643 * or the ability to modify system settings as determined by
1644 * {@link android.provider.Settings.System#canWrite}.</p>
1645 *
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001646 * @param networkType the type of the network over which traffic to the specified
1647 * host is to be routed
1648 * @param hostAddress the IP address of the host to which the route is desired
1649 * @return {@code true} on success, {@code false} on failure
1650 * @hide
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001651 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +09001652 * {@link #bindProcessToNetwork} API.
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001653 */
1654 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001655 checkLegacyRoutingApiAccess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001656 try {
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001657 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001658 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001659 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001660 }
1661 }
1662
1663 /**
1664 * Returns the value of the setting for background data usage. If false,
1665 * applications should not use the network if the application is not in the
1666 * foreground. Developers should respect this setting, and check the value
1667 * of this before performing any background data operations.
1668 * <p>
1669 * All applications that have background services that use the network
1670 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001671 * <p>
Scott Main4cc53332011-10-06 18:32:43 -07001672 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001673 * background data depends on several combined factors, and this method will
1674 * always return {@code true}. Instead, when background data is unavailable,
1675 * {@link #getActiveNetworkInfo()} will now appear disconnected.
Danica Chang6fdd0c62010-08-11 14:54:43 -07001676 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001677 * @return Whether background data usage is allowed.
1678 */
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001679 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001680 public boolean getBackgroundDataSetting() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001681 // assume that background data is allowed; final authority is
1682 // NetworkInfo which may be blocked.
1683 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001684 }
1685
1686 /**
1687 * Sets the value of the setting for background data usage.
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001688 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001689 * @param allowBackgroundData Whether an application should use data while
1690 * it is in the background.
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001691 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001692 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
1693 * @see #getBackgroundDataSetting()
1694 * @hide
1695 */
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001696 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001697 public void setBackgroundDataSetting(boolean allowBackgroundData) {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001698 // ignored
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001699 }
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001700
1701 /**
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001702 * Return quota status for the current active network, or {@code null} if no
1703 * network is active. Quota status can change rapidly, so these values
1704 * shouldn't be cached.
Jeff Sharkey44a3e0d2011-10-06 10:50:09 -07001705 *
Paul Jensen0d719ca2015-02-13 14:18:39 -05001706 * <p>This method requires the caller to hold the permission
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001707 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
1708 *
Jeff Sharkey44a3e0d2011-10-06 10:50:09 -07001709 * @hide
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001710 */
1711 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1712 try {
1713 return mService.getActiveNetworkQuotaInfo();
1714 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001715 throw e.rethrowFromSystemServer();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001716 }
1717 }
1718
1719 /**
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001720 * @hide
Robert Greenwaltafa05c02014-05-21 20:04:36 -07001721 * @deprecated Talk to TelephonyManager directly
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001722 */
1723 public boolean getMobileDataEnabled() {
Robert Greenwaltafa05c02014-05-21 20:04:36 -07001724 IBinder b = ServiceManager.getService(Context.TELEPHONY_SERVICE);
1725 if (b != null) {
1726 try {
1727 ITelephony it = ITelephony.Stub.asInterface(b);
Shishir Agrawal7ea3e8b2016-01-25 13:03:07 -08001728 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
Wink Saville36ffb042014-12-05 11:10:30 -08001729 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
1730 boolean retVal = it.getDataEnabled(subId);
1731 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
1732 + " retVal=" + retVal);
1733 return retVal;
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001734 } catch (RemoteException e) {
1735 throw e.rethrowFromSystemServer();
1736 }
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001737 }
Wink Saville36ffb042014-12-05 11:10:30 -08001738 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
Robert Greenwaltafa05c02014-05-21 20:04:36 -07001739 return false;
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001740 }
1741
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001742 /**
Robert Greenwaltb2489872014-09-04 16:44:35 -07001743 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
Robert Greenwalt6078b502014-06-11 16:05:07 -07001744 * to find out when the system default network has gone in to a high power state.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001745 */
1746 public interface OnNetworkActiveListener {
1747 /**
1748 * Called on the main thread of the process to report that the current data network
1749 * has become active, and it is now a good time to perform any pending network
1750 * operations. Note that this listener only tells you when the network becomes
1751 * active; if at any other time you want to know whether it is active (and thus okay
1752 * to initiate network traffic), you can retrieve its instantaneous state with
Robert Greenwalt6078b502014-06-11 16:05:07 -07001753 * {@link ConnectivityManager#isDefaultNetworkActive}.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001754 */
1755 public void onNetworkActive();
1756 }
1757
1758 private INetworkManagementService getNetworkManagementService() {
1759 synchronized (this) {
1760 if (mNMService != null) {
1761 return mNMService;
1762 }
1763 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
1764 mNMService = INetworkManagementService.Stub.asInterface(b);
1765 return mNMService;
1766 }
1767 }
1768
1769 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
1770 mNetworkActivityListeners
1771 = new ArrayMap<OnNetworkActiveListener, INetworkActivityListener>();
1772
1773 /**
Robert Greenwalt6078b502014-06-11 16:05:07 -07001774 * Start listening to reports when the system's default data network is active, meaning it is
1775 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
1776 * to determine the current state of the system's default network after registering the
1777 * listener.
1778 * <p>
1779 * If the process default network has been set with
Paul Jensen72db88e2015-03-10 10:54:12 -04001780 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
Robert Greenwalt6078b502014-06-11 16:05:07 -07001781 * reflect the process's default, but the system default.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001782 *
1783 * @param l The listener to be told when the network is active.
1784 */
Robert Greenwaltb2489872014-09-04 16:44:35 -07001785 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001786 INetworkActivityListener rl = new INetworkActivityListener.Stub() {
1787 @Override
1788 public void onNetworkActive() throws RemoteException {
1789 l.onNetworkActive();
1790 }
1791 };
1792
1793 try {
1794 getNetworkManagementService().registerNetworkActivityListener(rl);
1795 mNetworkActivityListeners.put(l, rl);
1796 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001797 throw e.rethrowFromSystemServer();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001798 }
1799 }
1800
1801 /**
1802 * Remove network active listener previously registered with
Robert Greenwaltb2489872014-09-04 16:44:35 -07001803 * {@link #addDefaultNetworkActiveListener}.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001804 *
1805 * @param l Previously registered listener.
1806 */
Robert Greenwaltb2489872014-09-04 16:44:35 -07001807 public void removeDefaultNetworkActiveListener(OnNetworkActiveListener l) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001808 INetworkActivityListener rl = mNetworkActivityListeners.get(l);
1809 if (rl == null) {
1810 throw new IllegalArgumentException("Listener not registered: " + l);
1811 }
1812 try {
1813 getNetworkManagementService().unregisterNetworkActivityListener(rl);
1814 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001815 throw e.rethrowFromSystemServer();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001816 }
1817 }
1818
1819 /**
1820 * Return whether the data network is currently active. An active network means that
1821 * it is currently in a high power state for performing data transmission. On some
1822 * types of networks, it may be expensive to move and stay in such a state, so it is
1823 * more power efficient to batch network traffic together when the radio is already in
1824 * this state. This method tells you whether right now is currently a good time to
1825 * initiate network traffic, as the network is already active.
1826 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07001827 public boolean isDefaultNetworkActive() {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001828 try {
1829 return getNetworkManagementService().isNetworkActive();
1830 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001831 throw e.rethrowFromSystemServer();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001832 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001833 }
1834
1835 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001836 * {@hide}
1837 */
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001838 public ConnectivityManager(Context context, IConnectivityManager service) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09001839 mContext = Preconditions.checkNotNull(context, "missing context");
1840 mService = Preconditions.checkNotNull(service, "missing IConnectivityManager");
Paul Jensene0bef712014-12-10 15:12:18 -05001841 sInstance = this;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001842 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001843
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001844 /** {@hide} */
1845 public static ConnectivityManager from(Context context) {
1846 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
1847 }
1848
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09001849 /* TODO: These permissions checks don't belong in client-side code. Move them to
1850 * services.jar, possibly in com.android.server.net. */
1851
1852 /** {@hide} */
1853 public static final boolean checkChangePermission(Context context) {
1854 int uid = Binder.getCallingUid();
1855 return Settings.checkAndNoteChangeNetworkStateOperation(context, uid, Settings
1856 .getPackageNameForUid(context, uid), false /* throwException */);
1857 }
1858
Lorenzo Colittid5427052015-10-15 16:29:00 +09001859 /** {@hide} */
1860 public static final void enforceChangePermission(Context context) {
1861 int uid = Binder.getCallingUid();
1862 Settings.checkAndNoteChangeNetworkStateOperation(context, uid, Settings
1863 .getPackageNameForUid(context, uid), true /* throwException */);
1864 }
1865
Robert Greenwaltedb47662014-09-16 17:54:19 -07001866 /** {@hide */
1867 public static final void enforceTetherChangePermission(Context context) {
1868 if (context.getResources().getStringArray(
1869 com.android.internal.R.array.config_mobile_hotspot_provision_app).length == 2) {
1870 // Have a provisioning app - must only let system apps (which check this app)
1871 // turn on tethering
1872 context.enforceCallingOrSelfPermission(
Jeremy Kleind42209d2015-12-28 15:11:58 -08001873 android.Manifest.permission.TETHER_PRIVILEGED, "ConnectivityService");
Robert Greenwaltedb47662014-09-16 17:54:19 -07001874 } else {
Billy Laua7238a32015-08-01 12:45:02 +01001875 int uid = Binder.getCallingUid();
Lorenzo Colittid5427052015-10-15 16:29:00 +09001876 Settings.checkAndNoteWriteSettingsOperation(context, uid, Settings
1877 .getPackageNameForUid(context, uid), true /* throwException */);
Robert Greenwaltedb47662014-09-16 17:54:19 -07001878 }
1879 }
1880
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001881 /**
Paul Jensene0bef712014-12-10 15:12:18 -05001882 * @deprecated - use getSystemService. This is a kludge to support static access in certain
1883 * situations where a Context pointer is unavailable.
1884 * @hide
1885 */
Paul Jensen72db88e2015-03-10 10:54:12 -04001886 static ConnectivityManager getInstanceOrNull() {
1887 return sInstance;
1888 }
1889
1890 /**
1891 * @deprecated - use getSystemService. This is a kludge to support static access in certain
1892 * situations where a Context pointer is unavailable.
1893 * @hide
1894 */
1895 private static ConnectivityManager getInstance() {
1896 if (getInstanceOrNull() == null) {
Paul Jensene0bef712014-12-10 15:12:18 -05001897 throw new IllegalStateException("No ConnectivityManager yet constructed");
1898 }
Paul Jensen72db88e2015-03-10 10:54:12 -04001899 return getInstanceOrNull();
Paul Jensene0bef712014-12-10 15:12:18 -05001900 }
1901
1902 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001903 * Get the set of tetherable, available interfaces. This list is limited by
1904 * device configuration and current interface existence.
Paul Jensenb2748922015-05-06 11:10:18 -04001905 * <p>This method requires the caller to hold the permission
1906 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001907 *
1908 * @return an array of 0 or more Strings of tetherable interface names.
1909 *
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001910 * {@hide}
1911 */
1912 public String[] getTetherableIfaces() {
1913 try {
1914 return mService.getTetherableIfaces();
1915 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001916 throw e.rethrowFromSystemServer();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001917 }
1918 }
1919
1920 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001921 * Get the set of tethered interfaces.
Paul Jensenb2748922015-05-06 11:10:18 -04001922 * <p>This method requires the caller to hold the permission
1923 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001924 *
1925 * @return an array of 0 or more String of currently tethered interface names.
1926 *
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001927 * {@hide}
1928 */
1929 public String[] getTetheredIfaces() {
1930 try {
1931 return mService.getTetheredIfaces();
1932 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001933 throw e.rethrowFromSystemServer();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001934 }
1935 }
1936
1937 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001938 * Get the set of interface names which attempted to tether but
1939 * failed. Re-attempting to tether may cause them to reset to the Tethered
1940 * state. Alternatively, causing the interface to be destroyed and recreated
1941 * may cause them to reset to the available state.
1942 * {@link ConnectivityManager#getLastTetherError} can be used to get more
1943 * information on the cause of the errors.
Paul Jensenb2748922015-05-06 11:10:18 -04001944 * <p>This method requires the caller to hold the permission
1945 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001946 *
1947 * @return an array of 0 or more String indicating the interface names
1948 * which failed to tether.
1949 *
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001950 * {@hide}
1951 */
Robert Greenwalt5a735062010-03-02 17:25:02 -08001952 public String[] getTetheringErroredIfaces() {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001953 try {
Robert Greenwalt5a735062010-03-02 17:25:02 -08001954 return mService.getTetheringErroredIfaces();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001955 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001956 throw e.rethrowFromSystemServer();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001957 }
1958 }
1959
1960 /**
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07001961 * Get the set of tethered dhcp ranges.
1962 *
1963 * @return an array of 0 or more {@code String} of tethered dhcp ranges.
1964 * {@hide}
1965 */
1966 public String[] getTetheredDhcpRanges() {
1967 try {
1968 return mService.getTetheredDhcpRanges();
1969 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001970 throw e.rethrowFromSystemServer();
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07001971 }
1972 }
1973
1974 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001975 * Attempt to tether the named interface. This will setup a dhcp server
1976 * on the interface, forward and NAT IP packets and forward DNS requests
1977 * to the best active upstream network interface. Note that if no upstream
1978 * IP network interface is available, dhcp will still run and traffic will be
1979 * allowed between the tethered devices and this device, though upstream net
1980 * access will of course fail until an upstream network interface becomes
1981 * active.
Lorenzo Colittid5427052015-10-15 16:29:00 +09001982 *
1983 * <p>This method requires the caller to hold either the
1984 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1985 * or the ability to modify system settings as determined by
1986 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001987 *
Jeremy Klein36c7aa02016-01-22 14:11:45 -08001988 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
1989 * and WifiStateMachine which need direct access. All other clients should use
1990 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
1991 * logic.</p>
1992 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001993 * @param iface the interface name to tether.
1994 * @return error a {@code TETHER_ERROR} value indicating success or failure type
1995 *
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001996 * {@hide}
1997 */
Robert Greenwalt5a735062010-03-02 17:25:02 -08001998 public int tether(String iface) {
1999 try {
2000 return mService.tether(iface);
2001 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002002 throw e.rethrowFromSystemServer();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002003 }
2004 }
2005
2006 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002007 * Stop tethering the named interface.
Lorenzo Colittid5427052015-10-15 16:29:00 +09002008 *
2009 * <p>This method requires the caller to hold either the
2010 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2011 * or the ability to modify system settings as determined by
2012 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002013 *
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002014 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2015 * and WifiStateMachine which need direct access. All other clients should use
2016 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2017 * logic.</p>
2018 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002019 * @param iface the interface name to untether.
2020 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2021 *
Robert Greenwalt5a735062010-03-02 17:25:02 -08002022 * {@hide}
2023 */
2024 public int untether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002025 try {
2026 return mService.untether(iface);
2027 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002028 throw e.rethrowFromSystemServer();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002029 }
2030 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002031
2032 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002033 * Check if the device allows for tethering. It may be disabled via
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002034 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002035 * due to device configuration.
Paul Jensenb2748922015-05-06 11:10:18 -04002036 * <p>This method requires the caller to hold the permission
2037 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002038 *
2039 * @return a boolean - {@code true} indicating Tethering is supported.
2040 *
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002041 * {@hide}
2042 */
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002043 @SystemApi
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002044 public boolean isTetheringSupported() {
2045 try {
2046 return mService.isTetheringSupported();
2047 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002048 throw e.rethrowFromSystemServer();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002049 }
2050 }
2051
2052 /**
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002053 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
2054 * @hide
2055 */
2056 @SystemApi
2057 public static abstract class OnStartTetheringCallback {
2058 /**
2059 * Called when tethering has been successfully started.
2060 */
2061 public void onTetheringStarted() {};
2062
2063 /**
2064 * Called when starting tethering failed.
2065 */
2066 public void onTetheringFailed() {};
2067 }
2068
2069 /**
2070 * Convenient overload for
2071 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
2072 * handler to run on the current thread's {@link Looper}.
2073 * @hide
2074 */
2075 @SystemApi
2076 public void startTethering(int type, boolean showProvisioningUi,
2077 final OnStartTetheringCallback callback) {
2078 startTethering(type, showProvisioningUi, callback, null);
2079 }
2080
2081 /**
2082 * Runs tether provisioning for the given type if needed and then starts tethering if
2083 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
2084 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
2085 * schedules tether provisioning re-checks if appropriate.
2086 *
2087 * @param type The type of tethering to start. Must be one of
2088 * {@link ConnectivityManager.TETHERING_WIFI},
2089 * {@link ConnectivityManager.TETHERING_USB}, or
2090 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2091 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
2092 * is one. This should be true the first time this function is called and also any time
2093 * the user can see this UI. It gives users information from their carrier about the
2094 * check failing and how they can sign up for tethering if possible.
2095 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
2096 * of the result of trying to tether.
2097 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
2098 * @hide
2099 */
2100 @SystemApi
2101 public void startTethering(int type, boolean showProvisioningUi,
2102 final OnStartTetheringCallback callback, Handler handler) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09002103 Preconditions.checkNotNull(callback, "OnStartTetheringCallback cannot be null.");
Jeremy Kleina17dabe2016-03-12 16:29:54 -08002104
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002105 ResultReceiver wrappedCallback = new ResultReceiver(handler) {
2106 @Override
2107 protected void onReceiveResult(int resultCode, Bundle resultData) {
2108 if (resultCode == TETHER_ERROR_NO_ERROR) {
2109 callback.onTetheringStarted();
2110 } else {
2111 callback.onTetheringFailed();
2112 }
2113 }
2114 };
Jeremy Kleina17dabe2016-03-12 16:29:54 -08002115
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002116 try {
2117 mService.startTethering(type, wrappedCallback, showProvisioningUi);
2118 } catch (RemoteException e) {
2119 Log.e(TAG, "Exception trying to start tethering.", e);
2120 wrappedCallback.send(TETHER_ERROR_SERVICE_UNAVAIL, null);
2121 }
2122 }
2123
2124 /**
2125 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
2126 * applicable.
2127 *
2128 * @param type The type of tethering to stop. Must be one of
2129 * {@link ConnectivityManager.TETHERING_WIFI},
2130 * {@link ConnectivityManager.TETHERING_USB}, or
2131 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2132 * @hide
2133 */
2134 @SystemApi
2135 public void stopTethering(int type) {
2136 try {
2137 mService.stopTethering(type);
2138 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002139 throw e.rethrowFromSystemServer();
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002140 }
2141 }
2142
2143 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002144 * Get the list of regular expressions that define any tetherable
2145 * USB network interfaces. If USB tethering is not supported by the
2146 * device, this list should be empty.
Paul Jensenb2748922015-05-06 11:10:18 -04002147 * <p>This method requires the caller to hold the permission
2148 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002149 *
2150 * @return an array of 0 or more regular expression Strings defining
2151 * what interfaces are considered tetherable usb interfaces.
2152 *
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002153 * {@hide}
2154 */
2155 public String[] getTetherableUsbRegexs() {
2156 try {
2157 return mService.getTetherableUsbRegexs();
2158 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002159 throw e.rethrowFromSystemServer();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002160 }
2161 }
2162
2163 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002164 * Get the list of regular expressions that define any tetherable
2165 * Wifi network interfaces. If Wifi tethering is not supported by the
2166 * device, this list should be empty.
Paul Jensenb2748922015-05-06 11:10:18 -04002167 * <p>This method requires the caller to hold the permission
2168 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002169 *
2170 * @return an array of 0 or more regular expression Strings defining
2171 * what interfaces are considered tetherable wifi interfaces.
2172 *
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002173 * {@hide}
2174 */
2175 public String[] getTetherableWifiRegexs() {
2176 try {
2177 return mService.getTetherableWifiRegexs();
2178 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002179 throw e.rethrowFromSystemServer();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002180 }
2181 }
Robert Greenwalt5a735062010-03-02 17:25:02 -08002182
Danica Chang6fdd0c62010-08-11 14:54:43 -07002183 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002184 * Get the list of regular expressions that define any tetherable
2185 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
2186 * device, this list should be empty.
Paul Jensenb2748922015-05-06 11:10:18 -04002187 * <p>This method requires the caller to hold the permission
2188 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002189 *
2190 * @return an array of 0 or more regular expression Strings defining
2191 * what interfaces are considered tetherable bluetooth interfaces.
2192 *
Danica Chang6fdd0c62010-08-11 14:54:43 -07002193 * {@hide}
2194 */
2195 public String[] getTetherableBluetoothRegexs() {
2196 try {
2197 return mService.getTetherableBluetoothRegexs();
2198 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002199 throw e.rethrowFromSystemServer();
Danica Chang6fdd0c62010-08-11 14:54:43 -07002200 }
2201 }
2202
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002203 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002204 * Attempt to both alter the mode of USB and Tethering of USB. A
2205 * utility method to deal with some of the complexity of USB - will
2206 * attempt to switch to Rndis and subsequently tether the resulting
2207 * interface on {@code true} or turn off tethering and switch off
2208 * Rndis on {@code false}.
Lorenzo Colittid5427052015-10-15 16:29:00 +09002209 *
2210 * <p>This method requires the caller to hold either the
2211 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2212 * or the ability to modify system settings as determined by
2213 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002214 *
2215 * @param enable a boolean - {@code true} to enable tethering
2216 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2217 *
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002218 * {@hide}
2219 */
2220 public int setUsbTethering(boolean enable) {
2221 try {
2222 return mService.setUsbTethering(enable);
2223 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002224 throw e.rethrowFromSystemServer();
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002225 }
2226 }
2227
Robert Greenwalt5a735062010-03-02 17:25:02 -08002228 /** {@hide} */
2229 public static final int TETHER_ERROR_NO_ERROR = 0;
2230 /** {@hide} */
2231 public static final int TETHER_ERROR_UNKNOWN_IFACE = 1;
2232 /** {@hide} */
2233 public static final int TETHER_ERROR_SERVICE_UNAVAIL = 2;
2234 /** {@hide} */
2235 public static final int TETHER_ERROR_UNSUPPORTED = 3;
2236 /** {@hide} */
2237 public static final int TETHER_ERROR_UNAVAIL_IFACE = 4;
2238 /** {@hide} */
2239 public static final int TETHER_ERROR_MASTER_ERROR = 5;
2240 /** {@hide} */
2241 public static final int TETHER_ERROR_TETHER_IFACE_ERROR = 6;
2242 /** {@hide} */
2243 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR = 7;
2244 /** {@hide} */
2245 public static final int TETHER_ERROR_ENABLE_NAT_ERROR = 8;
2246 /** {@hide} */
2247 public static final int TETHER_ERROR_DISABLE_NAT_ERROR = 9;
2248 /** {@hide} */
2249 public static final int TETHER_ERROR_IFACE_CFG_ERROR = 10;
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002250 /** {@hide} */
2251 public static final int TETHER_ERROR_PROVISION_FAILED = 11;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002252
2253 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002254 * Get a more detailed error code after a Tethering or Untethering
2255 * request asynchronously failed.
Paul Jensenb2748922015-05-06 11:10:18 -04002256 * <p>This method requires the caller to hold the permission
2257 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002258 *
2259 * @param iface The name of the interface of interest
Robert Greenwalt5a735062010-03-02 17:25:02 -08002260 * @return error The error code of the last error tethering or untethering the named
2261 * interface
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002262 *
Robert Greenwalt5a735062010-03-02 17:25:02 -08002263 * {@hide}
2264 */
2265 public int getLastTetherError(String iface) {
2266 try {
2267 return mService.getLastTetherError(iface);
2268 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002269 throw e.rethrowFromSystemServer();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002270 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002271 }
2272
2273 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002274 * Report network connectivity status. This is currently used only
2275 * to alter status bar UI.
Paul Jensenb2748922015-05-06 11:10:18 -04002276 * <p>This method requires the caller to hold the permission
2277 * {@link android.Manifest.permission#STATUS_BAR}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002278 *
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002279 * @param networkType The type of network you want to report on
2280 * @param percentage The quality of the connection 0 is bad, 100 is good
2281 * {@hide}
2282 */
2283 public void reportInetCondition(int networkType, int percentage) {
2284 try {
2285 mService.reportInetCondition(networkType, percentage);
2286 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002287 throw e.rethrowFromSystemServer();
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002288 }
2289 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002290
2291 /**
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002292 * Report a problem network to the framework. This provides a hint to the system
Ye Wenb87875e2014-07-21 14:19:01 -07002293 * that there might be connectivity problems on this network and may cause
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002294 * the framework to re-evaluate network connectivity and/or switch to another
2295 * network.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002296 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002297 * @param network The {@link Network} the application was attempting to use
2298 * or {@code null} to indicate the current default network.
Paul Jensenbfd17b72015-04-07 12:43:13 -04002299 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
2300 * working and non-working connectivity.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002301 */
2302 public void reportBadNetwork(Network network) {
2303 try {
Paul Jensenbfd17b72015-04-07 12:43:13 -04002304 // One of these will be ignored because it matches system's current state.
2305 // The other will trigger the necessary reevaluation.
2306 mService.reportNetworkConnectivity(network, true);
2307 mService.reportNetworkConnectivity(network, false);
2308 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002309 throw e.rethrowFromSystemServer();
Paul Jensenbfd17b72015-04-07 12:43:13 -04002310 }
2311 }
2312
2313 /**
2314 * Report to the framework whether a network has working connectivity.
2315 * This provides a hint to the system that a particular network is providing
2316 * working connectivity or not. In response the framework may re-evaluate
2317 * the network's connectivity and might take further action thereafter.
2318 *
2319 * @param network The {@link Network} the application was attempting to use
2320 * or {@code null} to indicate the current default network.
2321 * @param hasConnectivity {@code true} if the application was able to successfully access the
2322 * Internet using {@code network} or {@code false} if not.
2323 */
2324 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
2325 try {
2326 mService.reportNetworkConnectivity(network, hasConnectivity);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002327 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002328 throw e.rethrowFromSystemServer();
Robert Greenwalt9258c642014-03-26 16:47:06 -07002329 }
2330 }
2331
2332 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002333 * Set a network-independent global http proxy. This is not normally what you want
2334 * for typical HTTP proxies - they are general network dependent. However if you're
2335 * doing something unusual like general internal filtering this may be useful. On
2336 * a private network where the proxy is not accessible, you may break HTTP using this.
Paul Jensen0d719ca2015-02-13 14:18:39 -05002337 * <p>This method requires the caller to hold the permission
Jason Monkfaf3fd52014-05-07 18:41:13 -04002338 * android.Manifest.permission#CONNECTIVITY_INTERNAL.
Paul Jensenb2748922015-05-06 11:10:18 -04002339 *
2340 * @param p A {@link ProxyInfo} object defining the new global
2341 * HTTP proxy. A {@code null} value will clear the global HTTP proxy.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002342 * @hide
Robert Greenwalt434203a2010-10-11 16:00:27 -07002343 */
Jason Monk207900c2014-04-25 15:00:09 -04002344 public void setGlobalProxy(ProxyInfo p) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002345 try {
2346 mService.setGlobalProxy(p);
2347 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002348 throw e.rethrowFromSystemServer();
Robert Greenwalt434203a2010-10-11 16:00:27 -07002349 }
2350 }
2351
2352 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002353 * Retrieve any network-independent global HTTP proxy.
2354 *
Jason Monk207900c2014-04-25 15:00:09 -04002355 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002356 * if no global HTTP proxy is set.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002357 * @hide
Robert Greenwalt434203a2010-10-11 16:00:27 -07002358 */
Jason Monk207900c2014-04-25 15:00:09 -04002359 public ProxyInfo getGlobalProxy() {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002360 try {
2361 return mService.getGlobalProxy();
2362 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002363 throw e.rethrowFromSystemServer();
Robert Greenwalt434203a2010-10-11 16:00:27 -07002364 }
2365 }
2366
2367 /**
Paul Jensencee9b512015-05-06 07:32:40 -04002368 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
2369 * network-specific HTTP proxy. If {@code network} is null, the
2370 * network-specific proxy returned is the proxy of the default active
2371 * network.
2372 *
2373 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
2374 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
2375 * or when {@code network} is {@code null},
2376 * the {@code ProxyInfo} for the default active network. Returns
2377 * {@code null} when no proxy applies or the caller doesn't have
2378 * permission to use {@code network}.
2379 * @hide
2380 */
2381 public ProxyInfo getProxyForNetwork(Network network) {
2382 try {
2383 return mService.getProxyForNetwork(network);
2384 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002385 throw e.rethrowFromSystemServer();
Paul Jensencee9b512015-05-06 07:32:40 -04002386 }
2387 }
2388
2389 /**
Paul Jensene0bef712014-12-10 15:12:18 -05002390 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
2391 * otherwise if this process is bound to a {@link Network} using
Paul Jensen72db88e2015-03-10 10:54:12 -04002392 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
Paul Jensene0bef712014-12-10 15:12:18 -05002393 * the default network's proxy is returned.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002394 *
Jason Monk207900c2014-04-25 15:00:09 -04002395 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002396 * HTTP proxy is active.
Robert Greenwalt434203a2010-10-11 16:00:27 -07002397 */
Paul Jensene0bef712014-12-10 15:12:18 -05002398 public ProxyInfo getDefaultProxy() {
Paul Jensencee9b512015-05-06 07:32:40 -04002399 return getProxyForNetwork(getBoundNetworkForProcess());
Robert Greenwalt434203a2010-10-11 16:00:27 -07002400 }
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002401
2402 /**
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07002403 * Returns true if the hardware supports the given network type
2404 * else it returns false. This doesn't indicate we have coverage
2405 * or are authorized onto a network, just whether or not the
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002406 * hardware supports it. For example a GSM phone without a SIM
2407 * should still return {@code true} for mobile data, but a wifi only
2408 * tablet would return {@code false}.
Paul Jensenb2748922015-05-06 11:10:18 -04002409 * <p>This method requires the caller to hold the permission
2410 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002411 *
2412 * @param networkType The network type we'd like to check
2413 * @return {@code true} if supported, else {@code false}
2414 *
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07002415 * @hide
2416 */
2417 public boolean isNetworkSupported(int networkType) {
2418 try {
2419 return mService.isNetworkSupported(networkType);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002420 } catch (RemoteException e) {
2421 throw e.rethrowFromSystemServer();
2422 }
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07002423 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002424
2425 /**
2426 * Returns if the currently active data network is metered. A network is
2427 * classified as metered when the user is sensitive to heavy data usage on
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002428 * that connection due to monetary costs, data limitations or
2429 * battery/performance issues. You should check this before doing large
2430 * data transfers, and warn the user or delay the operation until another
2431 * network is available.
Paul Jensenb2748922015-05-06 11:10:18 -04002432 * <p>This method requires the caller to hold the permission
2433 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002434 *
2435 * @return {@code true} if large transfers should be avoided, otherwise
2436 * {@code false}.
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002437 */
2438 public boolean isActiveNetworkMetered() {
2439 try {
2440 return mService.isActiveNetworkMetered();
2441 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002442 throw e.rethrowFromSystemServer();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002443 }
2444 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002445
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002446 /**
2447 * If the LockdownVpn mechanism is enabled, updates the vpn
2448 * with a reload of its profile.
2449 *
2450 * @return a boolean with {@code} indicating success
2451 *
2452 * <p>This method can only be called by the system UID
2453 * {@hide}
2454 */
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002455 public boolean updateLockdownVpn() {
2456 try {
2457 return mService.updateLockdownVpn();
2458 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002459 throw e.rethrowFromSystemServer();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002460 }
2461 }
Irfan Sheriffda6da092012-08-16 12:49:23 -07002462
2463 /**
Wink Saville948282b2013-08-29 08:55:16 -07002464 * Check mobile provisioning.
Wink Savilleab9321d2013-06-29 21:10:57 -07002465 *
Wink Savilleab9321d2013-06-29 21:10:57 -07002466 * @param suggestedTimeOutMs, timeout in milliseconds
Wink Savilleab9321d2013-06-29 21:10:57 -07002467 *
2468 * @return time out that will be used, maybe less that suggestedTimeOutMs
2469 * -1 if an error.
2470 *
2471 * {@hide}
2472 */
Wink Saville948282b2013-08-29 08:55:16 -07002473 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Wink Savilleab9321d2013-06-29 21:10:57 -07002474 int timeOutMs = -1;
2475 try {
Wink Saville948282b2013-08-29 08:55:16 -07002476 timeOutMs = mService.checkMobileProvisioning(suggestedTimeOutMs);
Wink Savilleab9321d2013-06-29 21:10:57 -07002477 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002478 throw e.rethrowFromSystemServer();
Wink Savilleab9321d2013-06-29 21:10:57 -07002479 }
2480 return timeOutMs;
2481 }
Robert Greenwalte182bfe2013-07-16 12:06:09 -07002482
2483 /**
Wink Saville42d4f082013-07-20 20:31:59 -07002484 * Get the mobile provisioning url.
Robert Greenwalte182bfe2013-07-16 12:06:09 -07002485 * {@hide}
2486 */
2487 public String getMobileProvisioningUrl() {
2488 try {
2489 return mService.getMobileProvisioningUrl();
2490 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002491 throw e.rethrowFromSystemServer();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07002492 }
Robert Greenwalte182bfe2013-07-16 12:06:09 -07002493 }
Wink Saville42d4f082013-07-20 20:31:59 -07002494
2495 /**
Wink Saville948282b2013-08-29 08:55:16 -07002496 * Set sign in error notification to visible or in visible
2497 *
2498 * @param visible
2499 * @param networkType
2500 *
2501 * {@hide}
Paul Jensen3541e9f2015-03-18 12:23:02 -04002502 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
Wink Saville948282b2013-08-29 08:55:16 -07002503 */
2504 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04002505 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07002506 try {
Paul Jensen89e0f092014-09-15 15:59:36 -04002507 mService.setProvisioningNotificationVisible(visible, networkType, action);
Wink Saville948282b2013-08-29 08:55:16 -07002508 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002509 throw e.rethrowFromSystemServer();
Wink Saville948282b2013-08-29 08:55:16 -07002510 }
2511 }
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07002512
2513 /**
2514 * Set the value for enabling/disabling airplane mode
Paul Jensenb2748922015-05-06 11:10:18 -04002515 * <p>This method requires the caller to hold the permission
2516 * {@link android.Manifest.permission#CONNECTIVITY_INTERNAL}.
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07002517 *
2518 * @param enable whether to enable airplane mode or not
2519 *
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07002520 * @hide
2521 */
2522 public void setAirplaneMode(boolean enable) {
2523 try {
2524 mService.setAirplaneMode(enable);
2525 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002526 throw e.rethrowFromSystemServer();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07002527 }
2528 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002529
2530 /** {@hide} */
Robert Greenwalta67be032014-05-16 15:49:14 -07002531 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07002532 try {
Robert Greenwalta67be032014-05-16 15:49:14 -07002533 mService.registerNetworkFactory(messenger, name);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002534 } catch (RemoteException e) {
2535 throw e.rethrowFromSystemServer();
2536 }
Robert Greenwalta67be032014-05-16 15:49:14 -07002537 }
2538
2539 /** {@hide} */
2540 public void unregisterNetworkFactory(Messenger messenger) {
2541 try {
2542 mService.unregisterNetworkFactory(messenger);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002543 } catch (RemoteException e) {
2544 throw e.rethrowFromSystemServer();
2545 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002546 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002547
Paul Jensen31a94f42015-02-13 14:18:39 -05002548 /**
2549 * @hide
2550 * Register a NetworkAgent with ConnectivityService.
2551 * @return NetID corresponding to NetworkAgent.
2552 */
2553 public int registerNetworkAgent(Messenger messenger, NetworkInfo ni, LinkProperties lp,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07002554 NetworkCapabilities nc, int score, NetworkMisc misc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002555 try {
Paul Jensen31a94f42015-02-13 14:18:39 -05002556 return mService.registerNetworkAgent(messenger, ni, lp, nc, score, misc);
2557 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002558 throw e.rethrowFromSystemServer();
Paul Jensen31a94f42015-02-13 14:18:39 -05002559 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002560 }
2561
Robert Greenwalt9258c642014-03-26 16:47:06 -07002562 /**
Hugo Benichidafed3d2017-03-06 09:17:06 +09002563 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
2564 * changes. Should be extended by applications wanting notifications.
2565 *
2566 * A {@code NetworkCallback} is registered by calling
2567 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2568 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
2569 * or {@link #registerDefaultNetworkCallback(NetworkCallback). A {@code NetworkCallback} is
2570 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
2571 * A {@code NetworkCallback} should be registered at most once at any time.
2572 * A {@code NetworkCallback} that has been unregistered can be registered again.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002573 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07002574 public static class NetworkCallback {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002575 /**
Lorenzo Colitti07086932015-04-24 12:23:24 +09002576 * Called when the framework connects to a new network to evaluate whether it satisfies this
2577 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
2578 * callback. There is no guarantee that this new network will satisfy any requests, or that
2579 * the network will stay connected for longer than the time necessary to evaluate it.
2580 * <p>
2581 * Most applications <b>should not</b> act on this callback, and should instead use
2582 * {@link #onAvailable}. This callback is intended for use by applications that can assist
2583 * the framework in properly evaluating the network &mdash; for example, an application that
2584 * can automatically log in to a captive portal without user intervention.
2585 *
2586 * @param network The {@link Network} of the network that is being evaluated.
Lorenzo Colitti66276122015-06-11 14:27:17 +09002587 *
2588 * @hide
Robert Greenwalt7b816022014-04-18 15:25:25 -07002589 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07002590 public void onPreCheck(Network network) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07002591
2592 /**
Lorenzo Colitti07086932015-04-24 12:23:24 +09002593 * Called when the framework connects and has declared a new network ready for use.
Robert Greenwalt6078b502014-06-11 16:05:07 -07002594 * This callback may be called more than once if the {@link Network} that is
2595 * satisfying the request changes.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002596 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002597 * @param network The {@link Network} of the satisfying network.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002598 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07002599 public void onAvailable(Network network) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07002600
2601 /**
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002602 * Called when the network is about to be disconnected. Often paired with an
Robert Greenwalt6078b502014-06-11 16:05:07 -07002603 * {@link NetworkCallback#onAvailable} call with the new replacement network
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002604 * for graceful handover. This may not be called if we have a hard loss
2605 * (loss without warning). This may be followed by either a
Robert Greenwalt6078b502014-06-11 16:05:07 -07002606 * {@link NetworkCallback#onLost} call or a
2607 * {@link NetworkCallback#onAvailable} call for this network depending
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002608 * on whether we lose or regain it.
2609 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07002610 * @param network The {@link Network} that is about to be disconnected.
2611 * @param maxMsToLive The time in ms the framework will attempt to keep the
2612 * network connected. Note that the network may suffer a
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002613 * hard loss at any time.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002614 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07002615 public void onLosing(Network network, int maxMsToLive) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07002616
2617 /**
2618 * Called when the framework has a hard loss of the network or when the
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002619 * graceful failure ends.
2620 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002621 * @param network The {@link Network} lost.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002622 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07002623 public void onLost(Network network) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07002624
2625 /**
Etan Cohenaebf17e2017-03-01 12:47:28 -08002626 * Called if no network is found in the timeout time specified in
2627 * {@link #requestNetwork(NetworkRequest, int, NetworkCallback)} call. This callback is not
2628 * called for the version of {@link #requestNetwork(NetworkRequest, NetworkCallback)}
2629 * without timeout. When this callback is invoked the associated
2630 * {@link NetworkRequest} will have already been removed and released, as if
2631 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002632 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07002633 public void onUnavailable() {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07002634
2635 /**
2636 * Called when the network the framework connected to for this request
2637 * changes capabilities but still satisfies the stated need.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002638 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002639 * @param network The {@link Network} whose capabilities have changed.
Lorenzo Colittie285b432015-04-23 15:32:42 +09002640 * @param networkCapabilities The new {@link android.net.NetworkCapabilities} for this network.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002641 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07002642 public void onCapabilitiesChanged(Network network,
Robert Greenwalt7b816022014-04-18 15:25:25 -07002643 NetworkCapabilities networkCapabilities) {}
2644
2645 /**
2646 * Called when the network the framework connected to for this request
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002647 * changes {@link LinkProperties}.
2648 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002649 * @param network The {@link Network} whose link properties have changed.
2650 * @param linkProperties The new {@link LinkProperties} for this network.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002651 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07002652 public void onLinkPropertiesChanged(Network network, LinkProperties linkProperties) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07002653
Robert Greenwalt8d482522015-06-24 13:23:42 -07002654 /**
2655 * Called when the network the framework connected to for this request
2656 * goes into {@link NetworkInfo.DetailedState.SUSPENDED}.
2657 * This generally means that while the TCP connections are still live,
2658 * temporarily network data fails to transfer. Specifically this is used
2659 * on cellular networks to mask temporary outages when driving through
2660 * a tunnel, etc.
2661 * @hide
2662 */
2663 public void onNetworkSuspended(Network network) {}
2664
2665 /**
2666 * Called when the network the framework connected to for this request
2667 * returns from a {@link NetworkInfo.DetailedState.SUSPENDED} state.
2668 * This should always be preceeded by a matching {@code onNetworkSuspended}
2669 * call.
2670 * @hide
2671 */
2672 public void onNetworkResumed(Network network) {}
2673
Robert Greenwalt6078b502014-06-11 16:05:07 -07002674 private NetworkRequest networkRequest;
Hugo Benichidafed3d2017-03-06 09:17:06 +09002675
2676 private boolean isRegistered() {
2677 return (networkRequest != null) && (networkRequest.requestId != REQUEST_ID_UNSET);
2678 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002679 }
2680
Robert Greenwalt9258c642014-03-26 16:47:06 -07002681 private static final int BASE = Protocol.BASE_CONNECTIVITY_MANAGER;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002682 /** @hide */
Robert Greenwalt8d482522015-06-24 13:23:42 -07002683 public static final int CALLBACK_PRECHECK = BASE + 1;
2684 /** @hide */
2685 public static final int CALLBACK_AVAILABLE = BASE + 2;
2686 /** @hide arg1 = TTL */
2687 public static final int CALLBACK_LOSING = BASE + 3;
2688 /** @hide */
2689 public static final int CALLBACK_LOST = BASE + 4;
2690 /** @hide */
2691 public static final int CALLBACK_UNAVAIL = BASE + 5;
2692 /** @hide */
2693 public static final int CALLBACK_CAP_CHANGED = BASE + 6;
2694 /** @hide */
2695 public static final int CALLBACK_IP_CHANGED = BASE + 7;
Hugo Benichidafed3d2017-03-06 09:17:06 +09002696 // TODO: consider deleting CALLBACK_RELEASED and shifting following enum codes down by 1.
Robert Greenwalt8d482522015-06-24 13:23:42 -07002697 /** @hide */
2698 public static final int CALLBACK_RELEASED = BASE + 8;
Hugo Benichi1e19aef2016-07-07 10:15:56 +09002699 // TODO: consider deleting CALLBACK_EXIT and shifting following enum codes down by 1.
Robert Greenwalt8d482522015-06-24 13:23:42 -07002700 /** @hide */
2701 public static final int CALLBACK_EXIT = BASE + 9;
Robert Greenwalt562cc542014-05-15 18:07:26 -07002702 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Robert Greenwalt8d482522015-06-24 13:23:42 -07002703 private static final int EXPIRE_LEGACY_REQUEST = BASE + 10;
2704 /** @hide */
2705 public static final int CALLBACK_SUSPENDED = BASE + 11;
2706 /** @hide */
2707 public static final int CALLBACK_RESUMED = BASE + 12;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002708
Erik Kline95be6232015-11-25 12:49:38 +09002709 /** @hide */
2710 public static String getCallbackName(int whichCallback) {
2711 switch (whichCallback) {
2712 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
2713 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
2714 case CALLBACK_LOSING: return "CALLBACK_LOSING";
2715 case CALLBACK_LOST: return "CALLBACK_LOST";
2716 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
2717 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
2718 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
2719 case CALLBACK_RELEASED: return "CALLBACK_RELEASED";
2720 case CALLBACK_EXIT: return "CALLBACK_EXIT";
2721 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
2722 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
2723 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
2724 default:
2725 return Integer.toString(whichCallback);
2726 }
2727 }
2728
Robert Greenwalt562cc542014-05-15 18:07:26 -07002729 private class CallbackHandler extends Handler {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002730 private static final String TAG = "ConnectivityManager.CallbackHandler";
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07002731 private static final boolean DBG = false;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002732
Hugo Benichi9c58a112016-07-06 22:53:17 +09002733 CallbackHandler(Looper looper) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002734 super(looper);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002735 }
2736
Hugo Benichi2583ef02017-02-02 17:02:36 +09002737 CallbackHandler(Handler handler) {
2738 this(handler.getLooper());
2739 }
2740
Robert Greenwalt9258c642014-03-26 16:47:06 -07002741 @Override
2742 public void handleMessage(Message message) {
Hugo Benichi9c58a112016-07-06 22:53:17 +09002743 NetworkRequest request = getObject(message, NetworkRequest.class);
2744 Network network = getObject(message, Network.class);
Lorenzo Colittifcfa7d92016-03-01 22:56:37 +09002745 if (DBG) {
2746 Log.d(TAG, whatToString(message.what) + " for network " + network);
2747 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002748 switch (message.what) {
2749 case CALLBACK_PRECHECK: {
Lorenzo Colittidb95a602015-04-24 15:21:21 +09002750 NetworkCallback callback = getCallback(request, "PRECHECK");
2751 if (callback != null) {
2752 callback.onPreCheck(network);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002753 }
2754 break;
2755 }
2756 case CALLBACK_AVAILABLE: {
Lorenzo Colittidb95a602015-04-24 15:21:21 +09002757 NetworkCallback callback = getCallback(request, "AVAILABLE");
2758 if (callback != null) {
2759 callback.onAvailable(network);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002760 }
2761 break;
2762 }
2763 case CALLBACK_LOSING: {
Lorenzo Colittidb95a602015-04-24 15:21:21 +09002764 NetworkCallback callback = getCallback(request, "LOSING");
2765 if (callback != null) {
2766 callback.onLosing(network, message.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002767 }
2768 break;
2769 }
2770 case CALLBACK_LOST: {
Lorenzo Colittidb95a602015-04-24 15:21:21 +09002771 NetworkCallback callback = getCallback(request, "LOST");
2772 if (callback != null) {
2773 callback.onLost(network);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002774 }
2775 break;
2776 }
2777 case CALLBACK_UNAVAIL: {
Lorenzo Colittidb95a602015-04-24 15:21:21 +09002778 NetworkCallback callback = getCallback(request, "UNAVAIL");
2779 if (callback != null) {
2780 callback.onUnavailable();
Robert Greenwalt9258c642014-03-26 16:47:06 -07002781 }
2782 break;
2783 }
2784 case CALLBACK_CAP_CHANGED: {
Lorenzo Colittidb95a602015-04-24 15:21:21 +09002785 NetworkCallback callback = getCallback(request, "CAP_CHANGED");
2786 if (callback != null) {
Hugo Benichi9c58a112016-07-06 22:53:17 +09002787 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
Lorenzo Colittidb95a602015-04-24 15:21:21 +09002788 callback.onCapabilitiesChanged(network, cap);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002789 }
2790 break;
2791 }
2792 case CALLBACK_IP_CHANGED: {
Lorenzo Colittidb95a602015-04-24 15:21:21 +09002793 NetworkCallback callback = getCallback(request, "IP_CHANGED");
2794 if (callback != null) {
Hugo Benichi9c58a112016-07-06 22:53:17 +09002795 LinkProperties lp = getObject(message, LinkProperties.class);
Lorenzo Colittidb95a602015-04-24 15:21:21 +09002796 callback.onLinkPropertiesChanged(network, lp);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002797 }
2798 break;
2799 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07002800 case CALLBACK_SUSPENDED: {
2801 NetworkCallback callback = getCallback(request, "SUSPENDED");
2802 if (callback != null) {
2803 callback.onNetworkSuspended(network);
2804 }
2805 break;
2806 }
2807 case CALLBACK_RESUMED: {
2808 NetworkCallback callback = getCallback(request, "RESUMED");
2809 if (callback != null) {
2810 callback.onNetworkResumed(network);
2811 }
2812 break;
2813 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002814 case CALLBACK_RELEASED: {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002815 break;
2816 }
2817 case CALLBACK_EXIT: {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002818 break;
2819 }
Robert Greenwalt562cc542014-05-15 18:07:26 -07002820 case EXPIRE_LEGACY_REQUEST: {
2821 expireRequest((NetworkCapabilities)message.obj, message.arg1);
2822 break;
2823 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002824 }
2825 }
2826
Hugo Benichi9c58a112016-07-06 22:53:17 +09002827 private <T> T getObject(Message msg, Class<T> c) {
2828 return (T) msg.getData().getParcelable(c.getSimpleName());
Robert Greenwalt9258c642014-03-26 16:47:06 -07002829 }
Lorenzo Colittidb95a602015-04-24 15:21:21 +09002830
2831 private NetworkCallback getCallback(NetworkRequest req, String name) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09002832 final NetworkCallback callback;
Hugo Benichi9c58a112016-07-06 22:53:17 +09002833 synchronized(sCallbacks) {
2834 callback = sCallbacks.get(req);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002835 }
Lorenzo Colittidb95a602015-04-24 15:21:21 +09002836 if (callback == null) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09002837 Log.w(TAG, "callback not found for " + name + " message");
Lorenzo Colittidb95a602015-04-24 15:21:21 +09002838 }
2839 return callback;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002840 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002841 }
2842
Hugo Benichi2583ef02017-02-02 17:02:36 +09002843 private CallbackHandler getDefaultHandler() {
Hugo Benichi1e19aef2016-07-07 10:15:56 +09002844 synchronized (sCallbacks) {
2845 if (sCallbackHandler == null) {
2846 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
Robert Greenwalt9258c642014-03-26 16:47:06 -07002847 }
Hugo Benichi1e19aef2016-07-07 10:15:56 +09002848 return sCallbackHandler;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002849 }
2850 }
2851
Hugo Benichi6f260f32017-02-03 14:18:44 +09002852 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
2853 private static CallbackHandler sCallbackHandler;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002854
Hugo Benichi6f260f32017-02-03 14:18:44 +09002855 private static final int LISTEN = 1;
2856 private static final int REQUEST = 2;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002857
Hugo Benichi6f260f32017-02-03 14:18:44 +09002858 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
2859 int timeoutMs, int action, int legacyType, CallbackHandler handler) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09002860 Preconditions.checkArgument(callback != null, "null NetworkCallback");
2861 Preconditions.checkArgument(action == REQUEST || need != null, "null NetworkCapabilities");
Hugo Benichi9c58a112016-07-06 22:53:17 +09002862 final NetworkRequest request;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002863 try {
Hugo Benichi9c58a112016-07-06 22:53:17 +09002864 synchronized(sCallbacks) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09002865 if (callback.isRegistered()) {
2866 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
2867 // and requests (http://b/20701525).
2868 Log.e(TAG, "NetworkCallback was already registered");
2869 }
Hugo Benichi1e19aef2016-07-07 10:15:56 +09002870 Messenger messenger = new Messenger(handler);
Hugo Benichi9c58a112016-07-06 22:53:17 +09002871 Binder binder = new Binder();
Paul Jensen7221cc32014-06-27 11:05:32 -04002872 if (action == LISTEN) {
Hugo Benichi9c58a112016-07-06 22:53:17 +09002873 request = mService.listenForNetwork(need, messenger, binder);
Paul Jensen7221cc32014-06-27 11:05:32 -04002874 } else {
Hugo Benichi9c58a112016-07-06 22:53:17 +09002875 request = mService.requestNetwork(
2876 need, messenger, timeoutMs, binder, legacyType);
Paul Jensen7221cc32014-06-27 11:05:32 -04002877 }
Hugo Benichi9c58a112016-07-06 22:53:17 +09002878 if (request != null) {
Hugo Benichi1e19aef2016-07-07 10:15:56 +09002879 sCallbacks.put(request, callback);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002880 }
Hugo Benichi1e19aef2016-07-07 10:15:56 +09002881 callback.networkRequest = request;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002882 }
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002883 } catch (RemoteException e) {
2884 throw e.rethrowFromSystemServer();
2885 }
Hugo Benichi9c58a112016-07-06 22:53:17 +09002886 return request;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002887 }
2888
2889 /**
Erik Klinea2d29402016-03-16 15:31:39 +09002890 * Helper function to request a network with a particular legacy type.
Lorenzo Colitti7de289f2015-11-25 12:00:52 +09002891 *
2892 * This is temporarily public @hide so it can be called by system code that uses the
2893 * NetworkRequest API to request networks but relies on CONNECTIVITY_ACTION broadcasts for
2894 * instead network notifications.
2895 *
2896 * TODO: update said system code to rely on NetworkCallbacks and make this method private.
2897 *
2898 * @hide
2899 */
Lorenzo Colittid1179462015-11-25 15:47:14 +09002900 public void requestNetwork(NetworkRequest request, NetworkCallback networkCallback,
Hugo Benichi2583ef02017-02-02 17:02:36 +09002901 int timeoutMs, int legacyType, Handler handler) {
2902 CallbackHandler cbHandler = new CallbackHandler(handler);
2903 NetworkCapabilities nc = request.networkCapabilities;
2904 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
Lorenzo Colitti7de289f2015-11-25 12:00:52 +09002905 }
2906
2907 /**
Lorenzo Colittie285b432015-04-23 15:32:42 +09002908 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002909 *
2910 * This {@link NetworkRequest} will live until released via
Etan Cohenaebf17e2017-03-01 12:47:28 -08002911 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits. A
2912 * version of the method which takes a timeout is
2913 * {@link #requestNetwork(NetworkRequest, int, NetworkCallback)}.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002914 * Status of the request can be followed by listening to the various
Robert Greenwalt6078b502014-06-11 16:05:07 -07002915 * callbacks described in {@link NetworkCallback}. The {@link Network}
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002916 * can be used to direct traffic to the network.
Paul Jensenbb2e0e92015-06-16 15:11:58 -04002917 * <p>It is presently unsupported to request a network with mutable
2918 * {@link NetworkCapabilities} such as
2919 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
2920 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
2921 * as these {@code NetworkCapabilities} represent states that a particular
2922 * network may never attain, and whether a network will attain these states
2923 * is unknown prior to bringing up the network so the framework does not
2924 * know how to go about satisfing a request with these capabilities.
Lorenzo Colittid5427052015-10-15 16:29:00 +09002925 *
2926 * <p>This method requires the caller to hold either the
2927 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2928 * or the ability to modify system settings as determined by
2929 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt9258c642014-03-26 16:47:06 -07002930 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07002931 * @param request {@link NetworkRequest} describing this request.
Hugo Benichi2583ef02017-02-02 17:02:36 +09002932 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
2933 * the callback must not be shared - it uniquely specifies this request.
2934 * The callback is invoked on the default internal Handler.
Paul Jensenbb2e0e92015-06-16 15:11:58 -04002935 * @throws IllegalArgumentException if {@code request} specifies any mutable
2936 * {@code NetworkCapabilities}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002937 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07002938 public void requestNetwork(NetworkRequest request, NetworkCallback networkCallback) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09002939 requestNetwork(request, networkCallback, getDefaultHandler());
2940 }
2941
2942 /**
2943 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
2944 *
2945 * This {@link NetworkRequest} will live until released via
Etan Cohenaebf17e2017-03-01 12:47:28 -08002946 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits. A
2947 * version of the method which takes a timeout is
2948 * {@link #requestNetwork(NetworkRequest, int, NetworkCallback)}.
Hugo Benichi2583ef02017-02-02 17:02:36 +09002949 * Status of the request can be followed by listening to the various
2950 * callbacks described in {@link NetworkCallback}. The {@link Network}
2951 * can be used to direct traffic to the network.
2952 * <p>It is presently unsupported to request a network with mutable
2953 * {@link NetworkCapabilities} such as
2954 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
2955 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
2956 * as these {@code NetworkCapabilities} represent states that a particular
2957 * network may never attain, and whether a network will attain these states
2958 * is unknown prior to bringing up the network so the framework does not
2959 * know how to go about satisfing a request with these capabilities.
2960 *
2961 * <p>This method requires the caller to hold either the
2962 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2963 * or the ability to modify system settings as determined by
2964 * {@link android.provider.Settings.System#canWrite}.</p>
2965 *
2966 * @param request {@link NetworkRequest} describing this request.
2967 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
2968 * the callback must not be shared - it uniquely specifies this request.
2969 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
2970 * @throws IllegalArgumentException if {@code request} specifies any mutable
2971 * {@code NetworkCapabilities}.
Hugo Benichi2583ef02017-02-02 17:02:36 +09002972 */
2973 public void requestNetwork(
2974 NetworkRequest request, NetworkCallback networkCallback, Handler handler) {
2975 int legacyType = inferLegacyTypeForNetworkCapabilities(request.networkCapabilities);
2976 CallbackHandler cbHandler = new CallbackHandler(handler);
2977 requestNetwork(request, networkCallback, 0, legacyType, cbHandler);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002978 }
2979
2980 /**
Etan Cohenaebf17e2017-03-01 12:47:28 -08002981 * Note: this is a deprecated version of
2982 * {@link #requestNetwork(NetworkRequest, int, NetworkCallback)} - please transition code to use
2983 * the unhidden version of the function.
2984 * TODO: replace all callers with the new version of the API
2985 *
Lorenzo Colittie285b432015-04-23 15:32:42 +09002986 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
Robert Greenwalt9258c642014-03-26 16:47:06 -07002987 * by a timeout.
2988 *
Etan Cohenaebf17e2017-03-01 12:47:28 -08002989 * This function behaves identically to the non-timed-out version
2990 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
2991 * is not found within the given time (in milliseconds) the
2992 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
2993 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
2994 * not have to be released if timed-out (it is automatically released). Unregistering a
2995 * request that timed out is not an error.
2996 *
2997 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
2998 * timeout) - the {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
2999 * for that purpose. Calling this method will attempt to bring up the requested network.
Lorenzo Colittid5427052015-10-15 16:29:00 +09003000 *
3001 * <p>This method requires the caller to hold either the
3002 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3003 * or the ability to modify system settings as determined by
3004 * {@link android.provider.Settings.System#canWrite}.</p>
3005 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07003006 * @param request {@link NetworkRequest} describing this request.
Etan Cohenaebf17e2017-03-01 12:47:28 -08003007 * @param networkCallback The callbacks to be utilized for this request. Note
3008 * the callbacks must not be shared - they uniquely specify
3009 * this request.
Robert Greenwalt6078b502014-06-11 16:05:07 -07003010 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
Etan Cohenaebf17e2017-03-01 12:47:28 -08003011 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3012 * be a positive value (i.e. >0).
Robert Greenwalt9258c642014-03-26 16:47:06 -07003013 * @hide
3014 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07003015 public void requestNetwork(NetworkRequest request, NetworkCallback networkCallback,
3016 int timeoutMs) {
Etan Cohenaebf17e2017-03-01 12:47:28 -08003017 if (timeoutMs <= 0) {
3018 throw new IllegalArgumentException("Non-positive timeoutMs: " + timeoutMs);
3019 }
3020 int legacyType = inferLegacyTypeForNetworkCapabilities(request.networkCapabilities);
3021 requestNetwork(request, networkCallback, timeoutMs, legacyType, getDefaultHandler());
3022 }
3023
3024 /**
3025 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
3026 * by a timeout.
3027 *
3028 * This function behaves identically to the non-timed-out version
3029 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
3030 * is not found within the given time (in milliseconds) the
3031 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
3032 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
3033 * not have to be released if timed-out (it is automatically released). Unregistering a
3034 * request that timed out is not an error.
3035 *
3036 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
3037 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
3038 * for that purpose. Calling this method will attempt to bring up the requested network.
3039 *
3040 * <p>This method requires the caller to hold either the
3041 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3042 * or the ability to modify system settings as determined by
3043 * {@link android.provider.Settings.System#canWrite}.</p>
3044 *
3045 * @param request {@link NetworkRequest} describing this request.
3046 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3047 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3048 * be a positive value (i.e. >0).
3049 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3050 * the callback must not be shared - it uniquely specifies this request.
3051 */
3052 public void requestNetwork(NetworkRequest request, int timeoutMs,
3053 NetworkCallback networkCallback) {
3054 if (timeoutMs <= 0) {
3055 throw new IllegalArgumentException("Non-positive timeoutMs: " + timeoutMs);
3056 }
Hugo Benichi2583ef02017-02-02 17:02:36 +09003057 int legacyType = inferLegacyTypeForNetworkCapabilities(request.networkCapabilities);
Erik Klineb583b032017-02-22 12:58:24 +09003058 requestNetwork(request, networkCallback, timeoutMs, legacyType, getDefaultHandler());
Hugo Benichi2583ef02017-02-02 17:02:36 +09003059 }
3060
3061
3062 /**
3063 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
3064 * by a timeout.
3065 *
3066 * This function behaves identically to the non-timedout version, but if a suitable
3067 * network is not found within the given time (in milliseconds) the
Etan Cohenaebf17e2017-03-01 12:47:28 -08003068 * {@link NetworkCallback#onUnavailable} callback is called. The request can still be
3069 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
3070 * not have to be released if timed-out (it is automatically released). Unregistering a
3071 * request that timed out is not an error.
3072 *
3073 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
3074 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
3075 * for that purpose. Calling this method will attempt to bring up the requested network.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003076 *
3077 * <p>This method requires the caller to hold either the
3078 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3079 * or the ability to modify system settings as determined by
3080 * {@link android.provider.Settings.System#canWrite}.</p>
3081 *
3082 * @param request {@link NetworkRequest} describing this request.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003083 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3084 * before {@link NetworkCallback#onUnavailable} is called.
Etan Cohenaebf17e2017-03-01 12:47:28 -08003085 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3086 * the callback must not be shared - it uniquely specifies this request.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003087 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003088 */
Etan Cohenaebf17e2017-03-01 12:47:28 -08003089 public void requestNetwork(NetworkRequest request, int timeoutMs,
3090 NetworkCallback networkCallback, Handler handler) {
3091 if (timeoutMs <= 0) {
3092 throw new IllegalArgumentException("Non-positive timeoutMs");
3093 }
Hugo Benichi2583ef02017-02-02 17:02:36 +09003094 int legacyType = inferLegacyTypeForNetworkCapabilities(request.networkCapabilities);
3095 CallbackHandler cbHandler = new CallbackHandler(handler);
3096 requestNetwork(request, networkCallback, timeoutMs, legacyType, cbHandler);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003097 }
3098
3099 /**
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003100 * The lookup key for a {@link Network} object included with the intent after
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003101 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003102 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeremy Joslinfcde58f2015-02-11 16:51:13 -08003103 * <p>
Paul Jensen72db88e2015-03-10 10:54:12 -04003104 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
3105 * then you must get a ConnectivityManager instance before doing so.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003106 */
Erik Kline90e93072014-11-19 12:12:24 +09003107 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003108
3109 /**
Robert Greenwalt6078b502014-06-11 16:05:07 -07003110 * The lookup key for a {@link NetworkRequest} object included with the intent after
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003111 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003112 * {@link android.content.Intent#getParcelableExtra(String)}.
3113 */
Erik Kline90e93072014-11-19 12:12:24 +09003114 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003115
3116
3117 /**
Lorenzo Colittie285b432015-04-23 15:32:42 +09003118 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003119 *
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003120 * This function behaves identically to the version that takes a NetworkCallback, but instead
Robert Greenwalt6078b502014-06-11 16:05:07 -07003121 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003122 * the request may outlive the calling application and get called back when a suitable
3123 * network is found.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003124 * <p>
3125 * The operation is an Intent broadcast that goes to a broadcast receiver that
3126 * you registered with {@link Context#registerReceiver} or through the
3127 * &lt;receiver&gt; tag in an AndroidManifest.xml file
3128 * <p>
3129 * The operation Intent is delivered with two extras, a {@link Network} typed
Erik Kline90e93072014-11-19 12:12:24 +09003130 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
3131 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
Robert Greenwalt9258c642014-03-26 16:47:06 -07003132 * the original requests parameters. It is important to create a new,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003133 * {@link NetworkCallback} based request before completing the processing of the
Robert Greenwalt9258c642014-03-26 16:47:06 -07003134 * Intent to reserve the network or it will be released shortly after the Intent
3135 * is processed.
3136 * <p>
Paul Jensen694f2b82015-06-17 14:15:39 -04003137 * If there is already a request for this Intent registered (with the equality of
Robert Greenwalt9258c642014-03-26 16:47:06 -07003138 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003139 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003140 * <p>
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003141 * The request may be released normally by calling
3142 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003143 * <p>It is presently unsupported to request a network with either
3144 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3145 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3146 * as these {@code NetworkCapabilities} represent states that a particular
3147 * network may never attain, and whether a network will attain these states
3148 * is unknown prior to bringing up the network so the framework does not
3149 * know how to go about satisfing a request with these capabilities.
Lorenzo Colittid5427052015-10-15 16:29:00 +09003150 *
3151 * <p>This method requires the caller to hold either the
3152 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3153 * or the ability to modify system settings as determined by
3154 * {@link android.provider.Settings.System#canWrite}.</p>
3155 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07003156 * @param request {@link NetworkRequest} describing this request.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003157 * @param operation Action to perform when the network is available (corresponds
Robert Greenwalt6078b502014-06-11 16:05:07 -07003158 * to the {@link NetworkCallback#onAvailable} call. Typically
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003159 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003160 * @throws IllegalArgumentException if {@code request} contains either
3161 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3162 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003163 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07003164 public void requestNetwork(NetworkRequest request, PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003165 checkPendingIntent(operation);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003166 try {
Robert Greenwalt6078b502014-06-11 16:05:07 -07003167 mService.pendingRequestForNetwork(request.networkCapabilities, operation);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003168 } catch (RemoteException e) {
3169 throw e.rethrowFromSystemServer();
3170 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003171 }
3172
3173 /**
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003174 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
3175 * <p>
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09003176 * This method has the same behavior as
3177 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003178 * releasing network resources and disconnecting.
3179 *
3180 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
3181 * PendingIntent passed to
3182 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
3183 * corresponding NetworkRequest you'd like to remove. Cannot be null.
3184 */
3185 public void releaseNetworkRequest(PendingIntent operation) {
3186 checkPendingIntent(operation);
3187 try {
3188 mService.releasePendingNetworkRequest(operation);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003189 } catch (RemoteException e) {
3190 throw e.rethrowFromSystemServer();
3191 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003192 }
3193
3194 private void checkPendingIntent(PendingIntent intent) {
3195 if (intent == null) {
3196 throw new IllegalArgumentException("PendingIntent cannot be null.");
3197 }
3198 }
3199
3200 /**
Robert Greenwalt9258c642014-03-26 16:47:06 -07003201 * Registers to receive notifications about all networks which satisfy the given
Robert Greenwalt6078b502014-06-11 16:05:07 -07003202 * {@link NetworkRequest}. The callbacks will continue to be called until
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09003203 * either the application exits or link #unregisterNetworkCallback(NetworkCallback)} is called.
Paul Jensenb2748922015-05-06 11:10:18 -04003204 * <p>This method requires the caller to hold the permission
3205 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003206 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07003207 * @param request {@link NetworkRequest} describing this request.
3208 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
3209 * networks change state.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003210 * The callback is invoked on the default internal Handler.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003211 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07003212 public void registerNetworkCallback(NetworkRequest request, NetworkCallback networkCallback) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003213 registerNetworkCallback(request, networkCallback, getDefaultHandler());
3214 }
3215
3216 /**
3217 * Registers to receive notifications about all networks which satisfy the given
3218 * {@link NetworkRequest}. The callbacks will continue to be called until
3219 * either the application exits or link #unregisterNetworkCallback(NetworkCallback)} is called.
3220 * <p>This method requires the caller to hold the permission
3221 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
3222 *
3223 * @param request {@link NetworkRequest} describing this request.
3224 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
3225 * networks change state.
3226 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003227 */
3228 public void registerNetworkCallback(
3229 NetworkRequest request, NetworkCallback networkCallback, Handler handler) {
3230 CallbackHandler cbHandler = new CallbackHandler(handler);
3231 NetworkCapabilities nc = request.networkCapabilities;
3232 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003233 }
3234
3235 /**
Paul Jensen694f2b82015-06-17 14:15:39 -04003236 * Registers a PendingIntent to be sent when a network is available which satisfies the given
3237 * {@link NetworkRequest}.
3238 *
3239 * This function behaves identically to the version that takes a NetworkCallback, but instead
3240 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
3241 * the request may outlive the calling application and get called back when a suitable
3242 * network is found.
3243 * <p>
3244 * The operation is an Intent broadcast that goes to a broadcast receiver that
3245 * you registered with {@link Context#registerReceiver} or through the
3246 * &lt;receiver&gt; tag in an AndroidManifest.xml file
3247 * <p>
3248 * The operation Intent is delivered with two extras, a {@link Network} typed
3249 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
3250 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
3251 * the original requests parameters.
3252 * <p>
3253 * If there is already a request for this Intent registered (with the equality of
3254 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
3255 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
3256 * <p>
3257 * The request may be released normally by calling
Paul Jensenf2c1cfe2015-06-30 14:29:18 -04003258 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
Paul Jensen694f2b82015-06-17 14:15:39 -04003259 * <p>This method requires the caller to hold the permission
3260 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
3261 * @param request {@link NetworkRequest} describing this request.
3262 * @param operation Action to perform when the network is available (corresponds
3263 * to the {@link NetworkCallback#onAvailable} call. Typically
3264 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
3265 */
3266 public void registerNetworkCallback(NetworkRequest request, PendingIntent operation) {
3267 checkPendingIntent(operation);
3268 try {
3269 mService.pendingListenForNetwork(request.networkCapabilities, operation);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003270 } catch (RemoteException e) {
3271 throw e.rethrowFromSystemServer();
3272 }
Paul Jensen694f2b82015-06-17 14:15:39 -04003273 }
3274
3275 /**
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09003276 * Registers to receive notifications about changes in the system default network. The callbacks
3277 * will continue to be called until either the application exits or
3278 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Erik Klinea2d29402016-03-16 15:31:39 +09003279 * <p>This method requires the caller to hold the permission
3280 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
3281 *
3282 * @param networkCallback The {@link NetworkCallback} that the system will call as the
3283 * system default network changes.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003284 * The callback is invoked on the default internal Handler.
Erik Klinea2d29402016-03-16 15:31:39 +09003285 */
3286 public void registerDefaultNetworkCallback(NetworkCallback networkCallback) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003287 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
3288 }
3289
3290 /**
3291 * Registers to receive notifications about changes in the system default network. The callbacks
3292 * will continue to be called until either the application exits or
3293 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
3294 * <p>This method requires the caller to hold the permission
3295 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
3296 *
3297 * @param networkCallback The {@link NetworkCallback} that the system will call as the
3298 * system default network changes.
3299 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003300 */
3301 public void registerDefaultNetworkCallback(NetworkCallback networkCallback, Handler handler) {
Erik Klinea2d29402016-03-16 15:31:39 +09003302 // This works because if the NetworkCapabilities are null,
3303 // ConnectivityService takes them from the default request.
3304 //
3305 // Since the capabilities are exactly the same as the default request's
3306 // capabilities, this request is guaranteed, at all times, to be
3307 // satisfied by the same network, if any, that satisfies the default
3308 // request, i.e., the system default network.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003309 CallbackHandler cbHandler = new CallbackHandler(handler);
3310 sendRequestForNetwork(null, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
Erik Klinea2d29402016-03-16 15:31:39 +09003311 }
3312
3313 /**
fengludb571472015-04-21 17:12:05 -07003314 * Requests bandwidth update for a given {@link Network} and returns whether the update request
3315 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
3316 * network connection for updated bandwidth information. The caller will be notified via
3317 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09003318 * method assumes that the caller has previously called
3319 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
3320 * changes.
fenglub15e72b2015-03-20 11:29:56 -07003321 *
fengluae519192015-04-27 14:28:04 -07003322 * @param network {@link Network} specifying which network you're interested.
fengludb571472015-04-21 17:12:05 -07003323 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
fenglub15e72b2015-03-20 11:29:56 -07003324 */
fengludb571472015-04-21 17:12:05 -07003325 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07003326 try {
fengludb571472015-04-21 17:12:05 -07003327 return mService.requestBandwidthUpdate(network);
fenglub15e72b2015-03-20 11:29:56 -07003328 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003329 throw e.rethrowFromSystemServer();
fenglub15e72b2015-03-20 11:29:56 -07003330 }
3331 }
3332
3333 /**
Hugo Benichidafed3d2017-03-06 09:17:06 +09003334 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09003335 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
3336 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
3337 * If the given {@code NetworkCallback} had previously been used with
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +09003338 * {@code #requestNetwork}, any networks that had been connected to only to satisfy that request
3339 * will be disconnected.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003340 *
Hugo Benichidafed3d2017-03-06 09:17:06 +09003341 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
3342 * triggering it as soon as this call returns.
3343 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07003344 * @param networkCallback The {@link NetworkCallback} used when making the request.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003345 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07003346 public void unregisterNetworkCallback(NetworkCallback networkCallback) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09003347 Preconditions.checkArgument(networkCallback != null, "null NetworkCallback");
3348 final List<NetworkRequest> reqs = new ArrayList<>();
3349 // Find all requests associated to this callback and stop callback triggers immediately.
3350 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
3351 synchronized (sCallbacks) {
3352 Preconditions.checkArgument(
3353 networkCallback.isRegistered(), "NetworkCallback was not registered");
3354 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
3355 if (e.getValue() == networkCallback) {
3356 reqs.add(e.getKey());
3357 }
3358 }
3359 // TODO: throw exception if callback was registered more than once (http://b/20701525).
3360 for (NetworkRequest r : reqs) {
3361 try {
3362 mService.releaseNetworkRequest(r);
3363 } catch (RemoteException e) {
3364 throw e.rethrowFromSystemServer();
3365 }
3366 // Only remove mapping if rpc was successful.
3367 sCallbacks.remove(r);
3368 }
3369 networkCallback.networkRequest = null;
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003370 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003371 }
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04003372
3373 /**
Paul Jensenf2c1cfe2015-06-30 14:29:18 -04003374 * Unregisters a callback previously registered via
3375 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
3376 *
3377 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
3378 * PendingIntent passed to
3379 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
3380 * Cannot be null.
3381 */
3382 public void unregisterNetworkCallback(PendingIntent operation) {
3383 releaseNetworkRequest(operation);
3384 }
3385
3386 /**
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003387 * Informs the system whether it should switch to {@code network} regardless of whether it is
3388 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
3389 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
3390 * the system default network regardless of any other network that's currently connected. If
3391 * {@code always} is true, then the choice is remembered, so that the next time the user
3392 * connects to this network, the system will switch to it.
3393 *
3394 * <p>This method requires the caller to hold the permission
3395 * {@link android.Manifest.permission#CONNECTIVITY_INTERNAL}
3396 *
3397 * @param network The network to accept.
3398 * @param accept Whether to accept the network even if unvalidated.
3399 * @param always Whether to remember this choice in the future.
3400 *
3401 * @hide
3402 */
3403 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
3404 try {
3405 mService.setAcceptUnvalidated(network, accept, always);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003406 } catch (RemoteException e) {
3407 throw e.rethrowFromSystemServer();
3408 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003409 }
3410
3411 /**
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003412 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
3413 * only meaningful if the system is configured not to penalize such networks, e.g., if the
3414 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
3415 * NETWORK_AVOID_BAD_WIFI setting is unset}.
3416 *
3417 * <p>This method requires the caller to hold the permission
3418 * {@link android.Manifest.permission#CONNECTIVITY_INTERNAL}
3419 *
3420 * @param network The network to accept.
3421 *
3422 * @hide
3423 */
3424 public void setAvoidUnvalidated(Network network) {
3425 try {
3426 mService.setAvoidUnvalidated(network);
3427 } catch (RemoteException e) {
3428 throw e.rethrowFromSystemServer();
3429 }
3430 }
3431
3432 /**
Lorenzo Colitti46aa9c02017-01-24 18:08:41 +09003433 * It is acceptable to briefly use multipath data to provide seamless connectivity for
3434 * time-sensitive user-facing operations when the system default network is temporarily
3435 * unresponsive. The amount of data should be limited (less than one megabyte), and the
3436 * operation should be infrequent to ensure that data usage is limited.
3437 *
3438 * An example of such an operation might be a time-sensitive foreground activity, such as a
3439 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
3440 */
3441 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
3442
3443 /**
3444 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
3445 * a backup channel for traffic that is primarily going over another network.
3446 *
3447 * An example might be maintaining backup connections to peers or servers for the purpose of
3448 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
3449 * on backup paths should be negligible compared to the traffic on the main path.
3450 */
3451 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
3452
3453 /**
3454 * It is acceptable to use metered data to improve network latency and performance.
3455 */
3456 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
3457
3458 /**
3459 * Return value to use for unmetered networks. On such networks we currently set all the flags
3460 * to true.
3461 * @hide
3462 */
3463 public static final int MULTIPATH_PREFERENCE_UNMETERED =
3464 MULTIPATH_PREFERENCE_HANDOVER |
3465 MULTIPATH_PREFERENCE_RELIABILITY |
3466 MULTIPATH_PREFERENCE_PERFORMANCE;
3467
3468 /** @hide */
3469 @Retention(RetentionPolicy.SOURCE)
3470 @IntDef(flag = true, value = {
3471 MULTIPATH_PREFERENCE_HANDOVER,
3472 MULTIPATH_PREFERENCE_RELIABILITY,
3473 MULTIPATH_PREFERENCE_PERFORMANCE,
3474 })
3475 public @interface MultipathPreference {
3476 }
3477
3478 /**
3479 * Provides a hint to the calling application on whether it is desirable to use the
3480 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
3481 * for multipath data transfer on this network when it is not the system default network.
3482 * Applications desiring to use multipath network protocols should call this method before
3483 * each such operation.
3484 * <p>
3485 * This method requires the caller to hold the permission
3486 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
3487 *
3488 * @param network The network on which the application desires to use multipath data.
3489 * If {@code null}, this method will return the a preference that will generally
3490 * apply to metered networks.
3491 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
3492 */
3493 public @MultipathPreference int getMultipathPreference(Network network) {
3494 try {
3495 return mService.getMultipathPreference(network);
3496 } catch (RemoteException e) {
3497 throw e.rethrowFromSystemServer();
3498 }
3499 }
3500
3501 /**
Stuart Scott984dc852015-03-30 13:17:11 -07003502 * Resets all connectivity manager settings back to factory defaults.
3503 * @hide
3504 */
3505 public void factoryReset() {
Stuart Scott984dc852015-03-30 13:17:11 -07003506 try {
Stuart Scottf1fb3972015-04-02 18:00:02 -07003507 mService.factoryReset();
Stuart Scott984dc852015-03-30 13:17:11 -07003508 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003509 throw e.rethrowFromSystemServer();
Stuart Scott984dc852015-03-30 13:17:11 -07003510 }
3511 }
3512
3513 /**
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04003514 * Binds the current process to {@code network}. All Sockets created in the future
3515 * (and not explicitly bound via a bound SocketFactory from
3516 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
3517 * {@code network}. All host name resolutions will be limited to {@code network} as well.
3518 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
3519 * work and all host name resolutions will fail. This is by design so an application doesn't
3520 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
3521 * To clear binding pass {@code null} for {@code network}. Using individually bound
3522 * Sockets created by Network.getSocketFactory().createSocket() and
3523 * performing network-specific host name resolutions via
3524 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
Paul Jensen72db88e2015-03-10 10:54:12 -04003525 * {@code bindProcessToNetwork}.
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04003526 *
3527 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
3528 * the current binding.
3529 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
3530 */
Paul Jensen72db88e2015-03-10 10:54:12 -04003531 public boolean bindProcessToNetwork(Network network) {
3532 // Forcing callers to call thru non-static function ensures ConnectivityManager
3533 // instantiated.
3534 return setProcessDefaultNetwork(network);
3535 }
3536
3537 /**
3538 * Binds the current process to {@code network}. All Sockets created in the future
3539 * (and not explicitly bound via a bound SocketFactory from
3540 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
3541 * {@code network}. All host name resolutions will be limited to {@code network} as well.
3542 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
3543 * work and all host name resolutions will fail. This is by design so an application doesn't
3544 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
3545 * To clear binding pass {@code null} for {@code network}. Using individually bound
3546 * Sockets created by Network.getSocketFactory().createSocket() and
3547 * performing network-specific host name resolutions via
3548 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
3549 * {@code setProcessDefaultNetwork}.
3550 *
3551 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
3552 * the current binding.
3553 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
3554 * @deprecated This function can throw {@link IllegalStateException}. Use
3555 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
3556 * is a direct replacement.
3557 */
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04003558 public static boolean setProcessDefaultNetwork(Network network) {
Paul Jensenc91b5342014-08-27 12:38:45 -04003559 int netId = (network == null) ? NETID_UNSET : network.netId;
Paul Jensen72db88e2015-03-10 10:54:12 -04003560 if (netId == NetworkUtils.getBoundNetworkForProcess()) {
Paul Jensenc91b5342014-08-27 12:38:45 -04003561 return true;
3562 }
3563 if (NetworkUtils.bindProcessToNetwork(netId)) {
Paul Jensene0bef712014-12-10 15:12:18 -05003564 // Set HTTP proxy system properties to match network.
3565 // TODO: Deprecate this static method and replace it with a non-static version.
Lorenzo Colittiec4c5552015-04-22 11:52:48 +09003566 try {
3567 Proxy.setHttpProxySystemProperty(getInstance().getDefaultProxy());
3568 } catch (SecurityException e) {
3569 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
3570 Log.e(TAG, "Can't set proxy properties", e);
3571 }
Paul Jensenc91b5342014-08-27 12:38:45 -04003572 // Must flush DNS cache as new network may have different DNS resolutions.
3573 InetAddress.clearDnsCache();
3574 // Must flush socket pool as idle sockets will be bound to previous network and may
3575 // cause subsequent fetches to be performed on old network.
3576 NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
3577 return true;
3578 } else {
3579 return false;
3580 }
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04003581 }
3582
3583 /**
3584 * Returns the {@link Network} currently bound to this process via
Paul Jensen72db88e2015-03-10 10:54:12 -04003585 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04003586 *
3587 * @return {@code Network} to which this process is bound, or {@code null}.
3588 */
Paul Jensen72db88e2015-03-10 10:54:12 -04003589 public Network getBoundNetworkForProcess() {
3590 // Forcing callers to call thru non-static function ensures ConnectivityManager
3591 // instantiated.
3592 return getProcessDefaultNetwork();
3593 }
3594
3595 /**
3596 * Returns the {@link Network} currently bound to this process via
3597 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
3598 *
3599 * @return {@code Network} to which this process is bound, or {@code null}.
3600 * @deprecated Using this function can lead to other functions throwing
3601 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
3602 * {@code getBoundNetworkForProcess} is a direct replacement.
3603 */
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04003604 public static Network getProcessDefaultNetwork() {
Paul Jensen72db88e2015-03-10 10:54:12 -04003605 int netId = NetworkUtils.getBoundNetworkForProcess();
Paul Jensenbcc76d32014-07-11 08:17:29 -04003606 if (netId == NETID_UNSET) return null;
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04003607 return new Network(netId);
3608 }
3609
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09003610 private void unsupportedStartingFrom(int version) {
3611 if (Process.myUid() == Process.SYSTEM_UID) {
3612 // The getApplicationInfo() call we make below is not supported in system context, and
3613 // we want to allow the system to use these APIs anyway.
3614 return;
3615 }
3616
3617 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
3618 throw new UnsupportedOperationException(
3619 "This method is not supported in target SDK version " + version + " and above");
3620 }
3621 }
3622
3623 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
3624 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
Lifu Tang30f95a72016-01-07 23:20:38 -08003625 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09003626 // remove these exemptions. Note that this check is not secure, and apps can still access these
3627 // functions by accessing ConnectivityService directly. However, it should be clear that doing
3628 // so is unsupported and may break in the future. http://b/22728205
3629 private void checkLegacyRoutingApiAccess() {
3630 if (mContext.checkCallingOrSelfPermission("com.android.permission.INJECT_OMADM_SETTINGS")
3631 == PackageManager.PERMISSION_GRANTED) {
3632 return;
3633 }
3634
Dianne Hackborn692a2442015-07-31 10:35:34 -07003635 unsupportedStartingFrom(VERSION_CODES.M);
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09003636 }
3637
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04003638 /**
3639 * Binds host resolutions performed by this process to {@code network}.
Paul Jensen72db88e2015-03-10 10:54:12 -04003640 * {@link #bindProcessToNetwork} takes precedence over this setting.
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04003641 *
3642 * @param network The {@link Network} to bind host resolutions from the current process to, or
3643 * {@code null} to clear the current binding.
3644 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
3645 * @hide
3646 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
3647 */
3648 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
Paul Jensenbcc76d32014-07-11 08:17:29 -04003649 return NetworkUtils.bindProcessToNetworkForHostResolution(
3650 network == null ? NETID_UNSET : network.netId);
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04003651 }
Felipe Leme1b103232016-01-22 09:44:57 -08003652
3653 /**
3654 * Device is not restricting metered network activity while application is running on
3655 * background.
3656 */
3657 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
3658
3659 /**
3660 * Device is restricting metered network activity while application is running on background,
3661 * but application is allowed to bypass it.
3662 * <p>
3663 * In this state, application should take action to mitigate metered network access.
3664 * For example, a music streaming application should switch to a low-bandwidth bitrate.
3665 */
3666 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
3667
3668 /**
3669 * Device is restricting metered network activity while application is running on background.
Felipe Leme9778f762016-01-27 14:46:39 -08003670 * <p>
Felipe Leme1b103232016-01-22 09:44:57 -08003671 * In this state, application should not try to use the network while running on background,
3672 * because it would be denied.
3673 */
3674 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
3675
Felipe Leme9778f762016-01-27 14:46:39 -08003676 /**
3677 * A change in the background metered network activity restriction has occurred.
3678 * <p>
3679 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
3680 * applies to them.
3681 * <p>
3682 * This is only sent to registered receivers, not manifest receivers.
3683 */
3684 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
3685 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
3686 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
3687
Felipe Lemeecfccea2016-01-25 11:48:04 -08003688 /** @hide */
3689 @Retention(RetentionPolicy.SOURCE)
Felipe Leme1b103232016-01-22 09:44:57 -08003690 @IntDef(flag = false, value = {
3691 RESTRICT_BACKGROUND_STATUS_DISABLED,
3692 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
3693 RESTRICT_BACKGROUND_STATUS_ENABLED,
3694 })
Felipe Leme1b103232016-01-22 09:44:57 -08003695 public @interface RestrictBackgroundStatus {
3696 }
3697
3698 private INetworkPolicyManager getNetworkPolicyManager() {
3699 synchronized (this) {
3700 if (mNPManager != null) {
3701 return mNPManager;
3702 }
3703 mNPManager = INetworkPolicyManager.Stub.asInterface(ServiceManager
3704 .getService(Context.NETWORK_POLICY_SERVICE));
3705 return mNPManager;
3706 }
3707 }
3708
3709 /**
3710 * Determines if the calling application is subject to metered network restrictions while
3711 * running on background.
Felipe Lemec9c7be52016-05-16 13:57:19 -07003712 *
3713 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
3714 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
3715 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
Felipe Leme1b103232016-01-22 09:44:57 -08003716 */
3717 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
3718 try {
3719 return getNetworkPolicyManager().getRestrictBackgroundByCaller();
3720 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003721 throw e.rethrowFromSystemServer();
Felipe Leme1b103232016-01-22 09:44:57 -08003722 }
3723 }
Andreas Gampe34802132016-04-20 14:33:51 -07003724
3725 /**
3726 * A holder class for debug info (mapping CALLBACK values to field names). This is stored
3727 * in a holder for two reasons:
3728 * 1) The reflection necessary to establish the map can't be run at compile-time. Thus, this
3729 * code will make the enclosing class not compile-time initializeable, deferring its
3730 * initialization to zygote startup. This leads to dirty (but shared) memory.
3731 * As this is debug info, use a holder that isn't initialized by default. This way the map
3732 * will be created on demand, while ConnectivityManager can be compile-time initialized.
3733 * 2) Static initialization is still preferred for its strong thread safety guarantees without
3734 * requiring a lock.
3735 */
3736 private static class NoPreloadHolder {
3737 public static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
3738 new Class[]{ConnectivityManager.class}, new String[]{"CALLBACK_"});
3739 }
3740
3741 static {
3742 // When debug is enabled, aggressively initialize the holder by touching the field (which
3743 // will guarantee static initialization).
3744 if (CallbackHandler.DBG) {
3745 Object dummy = NoPreloadHolder.sMagicDecoderRing;
3746 }
3747 }
3748
3749 private static final String whatToString(int what) {
3750 return NoPreloadHolder.sMagicDecoderRing.get(what, Integer.toString(what));
3751 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003752}