blob: 02f0f184b903ca799a56f30bd1bf000272bd529c [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;
Lorenzo Colitti2965d332017-04-27 14:30:21 +090020import android.annotation.RequiresPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080021import android.annotation.SdkConstant;
22import android.annotation.SdkConstant.SdkConstantType;
Udam Sainib7c24872016-01-04 12:16:14 -080023import android.annotation.SystemApi;
Robert Greenwalt9258c642014-03-26 16:47:06 -070024import android.app.PendingIntent;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -070025import android.content.Context;
Robert Greenwaltd19c41c2014-05-18 23:07:25 -070026import android.content.Intent;
Lorenzo Colittiffc42b02015-07-29 11:41:21 +090027import android.content.pm.PackageManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -070028import android.os.Binder;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -070029import android.os.Build.VERSION_CODES;
Jeremy Klein36c7aa02016-01-22 14:11:45 -080030import android.os.Bundle;
Robert Greenwalt9258c642014-03-26 16:47:06 -070031import android.os.Handler;
32import android.os.HandlerThread;
Dianne Hackborn77b987f2014-02-26 16:20:52 -080033import android.os.IBinder;
34import android.os.INetworkActivityListener;
35import android.os.INetworkManagementService;
Robert Greenwalt9258c642014-03-26 16:47:06 -070036import android.os.Looper;
37import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070038import android.os.Messenger;
Lorenzo Colittiffc42b02015-07-29 11:41:21 +090039import android.os.Process;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080040import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -080041import android.os.ResultReceiver;
Dianne Hackborn77b987f2014-02-26 16:20:52 -080042import android.os.ServiceManager;
Hugo Benichicb883232017-05-11 13:16:17 +090043import android.os.ServiceSpecificException;
Jeff Sharkey961e3042011-08-29 16:02:57 -070044import android.provider.Settings;
Wink Saville36ffb042014-12-05 11:10:30 -080045import android.telephony.SubscriptionManager;
Dianne Hackborn77b987f2014-02-26 16:20:52 -080046import android.util.ArrayMap;
Robert Greenwalt9258c642014-03-26 16:47:06 -070047import android.util.Log;
Erik Kline35bf06c2017-01-26 18:08:28 +090048import android.util.SparseIntArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049
Robert Greenwaltafa05c02014-05-21 20:04:36 -070050import com.android.internal.telephony.ITelephony;
Robert Greenwalt562cc542014-05-15 18:07:26 -070051import com.android.internal.telephony.PhoneConstants;
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},
Erik Kline8351faa2017-04-17 16:47:23 +0900305 * {@code ConnectivityManager.EXTRA_ACTIVE_LOCAL_ONLY},
306 * {@code ConnectivityManager.EXTRA_ACTIVE_TETHER}, and
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800307 * {@code ConnectivityManager.EXTRA_ERRORED_TETHER} to indicate
308 * the current state of tethering. Each include a list of
309 * interface names in that state (may be empty).
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800310 * @hide
311 */
Jeff Sharkey4fa63b22013-02-20 18:21:19 -0800312 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800313 public static final String ACTION_TETHER_STATE_CHANGED =
314 "android.net.conn.TETHER_STATE_CHANGED";
315
316 /**
317 * @hide
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800318 * gives a String[] listing all the interfaces configured for
319 * tethering and currently available for tethering.
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800320 */
Robert Greenwalt2a091d72010-02-11 18:18:40 -0800321 public static final String EXTRA_AVAILABLE_TETHER = "availableArray";
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800322
323 /**
324 * @hide
Erik Kline8351faa2017-04-17 16:47:23 +0900325 * gives a String[] listing all the interfaces currently in local-only
326 * mode (ie, has DHCPv4+IPv6-ULA support and no packet forwarding)
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800327 */
Erik Kline8351faa2017-04-17 16:47:23 +0900328 public static final String EXTRA_ACTIVE_LOCAL_ONLY = "localOnlyArray";
329
330 /**
331 * @hide
332 * gives a String[] listing all the interfaces currently tethered
333 * (ie, has DHCPv4 support and packets potentially forwarded/NATed)
334 */
335 public static final String EXTRA_ACTIVE_TETHER = "tetherArray";
Robert Greenwalt2a091d72010-02-11 18:18:40 -0800336
337 /**
338 * @hide
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800339 * gives a String[] listing all the interfaces we tried to tether and
340 * failed. Use {@link #getLastTetherError} to find the error code
341 * for any interfaces listed here.
Robert Greenwalt2a091d72010-02-11 18:18:40 -0800342 */
343 public static final String EXTRA_ERRORED_TETHER = "erroredArray";
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800344
345 /**
Russell Brenner108da0c2013-02-12 10:03:14 -0800346 * Broadcast Action: The captive portal tracker has finished its test.
347 * Sent only while running Setup Wizard, in lieu of showing a user
348 * notification.
349 * @hide
350 */
Jeff Sharkey4fa63b22013-02-20 18:21:19 -0800351 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Russell Brenner108da0c2013-02-12 10:03:14 -0800352 public static final String ACTION_CAPTIVE_PORTAL_TEST_COMPLETED =
353 "android.net.conn.CAPTIVE_PORTAL_TEST_COMPLETED";
354 /**
355 * The lookup key for a boolean that indicates whether a captive portal was detected.
356 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
357 * @hide
358 */
359 public static final String EXTRA_IS_CAPTIVE_PORTAL = "captivePortal";
360
361 /**
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900362 * Action used to display a dialog that asks the user whether to connect to a network that is
363 * not validated. This intent is used to start the dialog in settings via startActivity.
364 *
365 * @hide
366 */
367 public static final String ACTION_PROMPT_UNVALIDATED = "android.net.conn.PROMPT_UNVALIDATED";
368
369 /**
Lorenzo Colitti9be58c52016-09-15 14:02:29 +0900370 * Action used to display a dialog that asks the user whether to avoid a network that is no
371 * longer validated. This intent is used to start the dialog in settings via startActivity.
372 *
373 * @hide
374 */
375 public static final String ACTION_PROMPT_LOST_VALIDATION =
376 "android.net.conn.PROMPT_LOST_VALIDATION";
377
378 /**
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800379 * Invalid tethering type.
380 * @see #startTethering(int, OnStartTetheringCallback, boolean)
381 * @hide
382 */
383 public static final int TETHERING_INVALID = -1;
384
385 /**
386 * Wifi tethering type.
387 * @see #startTethering(int, OnStartTetheringCallback, boolean)
388 * @hide
389 */
390 @SystemApi
391 public static final int TETHERING_WIFI = 0;
392
393 /**
394 * USB tethering type.
395 * @see #startTethering(int, OnStartTetheringCallback, boolean)
396 * @hide
397 */
398 @SystemApi
399 public static final int TETHERING_USB = 1;
400
401 /**
402 * Bluetooth tethering type.
403 * @see #startTethering(int, OnStartTetheringCallback, boolean)
404 * @hide
405 */
406 @SystemApi
407 public static final int TETHERING_BLUETOOTH = 2;
408
409 /**
410 * Extra used for communicating with the TetherService. Includes the type of tethering to
411 * enable if any.
412 * @hide
413 */
414 public static final String EXTRA_ADD_TETHER_TYPE = "extraAddTetherType";
415
416 /**
417 * Extra used for communicating with the TetherService. Includes the type of tethering for
418 * which to cancel provisioning.
419 * @hide
420 */
421 public static final String EXTRA_REM_TETHER_TYPE = "extraRemTetherType";
422
423 /**
424 * Extra used for communicating with the TetherService. True to schedule a recheck of tether
425 * provisioning.
426 * @hide
427 */
428 public static final String EXTRA_SET_ALARM = "extraSetAlarm";
429
430 /**
431 * Tells the TetherService to run a provision check now.
432 * @hide
433 */
434 public static final String EXTRA_RUN_PROVISION = "extraRunProvision";
435
436 /**
437 * Extra used for communicating with the TetherService. Contains the {@link ResultReceiver}
438 * which will receive provisioning results. Can be left empty.
439 * @hide
440 */
441 public static final String EXTRA_PROVISION_CALLBACK = "extraProvisionCallback";
442
443 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800444 * The absence of a connection type.
Robert Greenwaltccf83af12011-06-02 17:30:47 -0700445 * @hide
446 */
447 public static final int TYPE_NONE = -1;
448
449 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800450 * The Mobile data connection. When active, all data traffic
451 * will use this network type's interface by default
452 * (it has a default route)
Robert Greenwalt42acef32009-08-12 16:08:25 -0700453 */
454 public static final int TYPE_MOBILE = 0;
455 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800456 * The WIFI data connection. When active, all data traffic
457 * will use this network type's interface by default
458 * (it has a default route).
Robert Greenwalt42acef32009-08-12 16:08:25 -0700459 */
460 public static final int TYPE_WIFI = 1;
461 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800462 * An MMS-specific Mobile data connection. This network type may use the
463 * same network interface as {@link #TYPE_MOBILE} or it may use a different
464 * one. This is used by applications needing to talk to the carrier's
465 * Multimedia Messaging Service servers.
Lorenzo Colittie285b432015-04-23 15:32:42 +0900466 *
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +0900467 * @deprecated Applications should instead use
468 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colittie285b432015-04-23 15:32:42 +0900469 * provides the {@link NetworkCapabilities#NET_CAPABILITY_MMS} capability.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700470 */
471 public static final int TYPE_MOBILE_MMS = 2;
472 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800473 * A SUPL-specific Mobile data connection. This network type may use the
474 * same network interface as {@link #TYPE_MOBILE} or it may use a different
475 * one. This is used by applications needing to talk to the carrier's
476 * Secure User Plane Location servers for help locating the device.
Lorenzo Colittie285b432015-04-23 15:32:42 +0900477 *
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +0900478 * @deprecated Applications should instead use
479 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colittie285b432015-04-23 15:32:42 +0900480 * provides the {@link NetworkCapabilities#NET_CAPABILITY_SUPL} capability.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700481 */
482 public static final int TYPE_MOBILE_SUPL = 3;
483 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800484 * A DUN-specific Mobile data connection. This network type may use the
485 * same network interface as {@link #TYPE_MOBILE} or it may use a different
486 * one. This is sometimes by the system when setting up an upstream connection
487 * for tethering so that the carrier is aware of DUN traffic.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700488 */
489 public static final int TYPE_MOBILE_DUN = 4;
490 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800491 * A High Priority Mobile data connection. This network type uses the
492 * same network interface as {@link #TYPE_MOBILE} but the routing setup
Lorenzo Colittie285b432015-04-23 15:32:42 +0900493 * is different.
494 *
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +0900495 * @deprecated Applications should instead use
496 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colittie285b432015-04-23 15:32:42 +0900497 * uses the {@link NetworkCapabilities#TRANSPORT_CELLULAR} transport.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700498 */
499 public static final int TYPE_MOBILE_HIPRI = 5;
jsh8214deb2010-03-11 15:04:43 -0800500 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800501 * The WiMAX data connection. When active, all data traffic
502 * will use this network type's interface by default
503 * (it has a default route).
jsh8214deb2010-03-11 15:04:43 -0800504 */
505 public static final int TYPE_WIMAX = 6;
Robert Greenwaltda3d5e62010-12-06 13:56:24 -0800506
Jaikumar Ganesh15c74392010-12-21 22:31:44 -0800507 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800508 * The Bluetooth data connection. When active, all data traffic
509 * will use this network type's interface by default
510 * (it has a default route).
Jaikumar Ganesh15c74392010-12-21 22:31:44 -0800511 */
512 public static final int TYPE_BLUETOOTH = 7;
513
Robert Greenwalt60810842011-04-22 15:28:18 -0700514 /**
515 * Dummy data connection. This should not be used on shipping devices.
516 */
Jaikumar Ganesh15c74392010-12-21 22:31:44 -0800517 public static final int TYPE_DUMMY = 8;
Wink Saville9d7d6282011-03-12 14:52:01 -0800518
Robert Greenwalt60810842011-04-22 15:28:18 -0700519 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800520 * The Ethernet data connection. When active, all data traffic
521 * will use this network type's interface by default
522 * (it has a default route).
Robert Greenwalt60810842011-04-22 15:28:18 -0700523 */
Robert Greenwalte12aec92011-01-28 14:48:37 -0800524 public static final int TYPE_ETHERNET = 9;
Robert Greenwalt60810842011-04-22 15:28:18 -0700525
Wink Saville9d7d6282011-03-12 14:52:01 -0800526 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800527 * Over the air Administration.
Wink Saville9d7d6282011-03-12 14:52:01 -0800528 * {@hide}
529 */
530 public static final int TYPE_MOBILE_FOTA = 10;
531
532 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800533 * IP Multimedia Subsystem.
Wink Saville9d7d6282011-03-12 14:52:01 -0800534 * {@hide}
535 */
536 public static final int TYPE_MOBILE_IMS = 11;
537
538 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800539 * Carrier Branded Services.
Wink Saville9d7d6282011-03-12 14:52:01 -0800540 * {@hide}
541 */
542 public static final int TYPE_MOBILE_CBS = 12;
543
repo syncaea743a2011-07-29 23:55:49 -0700544 /**
545 * A Wi-Fi p2p connection. Only requesting processes will have access to
546 * the peers connected.
547 * {@hide}
548 */
549 public static final int TYPE_WIFI_P2P = 13;
Wink Saville9d7d6282011-03-12 14:52:01 -0800550
Wink Saville5e56bc52013-07-29 15:00:57 -0700551 /**
552 * The network to use for initially attaching to the network
553 * {@hide}
554 */
555 public static final int TYPE_MOBILE_IA = 14;
repo syncaea743a2011-07-29 23:55:49 -0700556
Lorenzo Colittie285b432015-04-23 15:32:42 +0900557 /**
Robert Greenwalt4bd43892015-07-09 14:49:35 -0700558 * Emergency PDN connection for emergency services. This
559 * may include IMS and MMS in emergency situations.
Ram3e0e3bc2014-06-26 11:03:44 -0700560 * {@hide}
561 */
562 public static final int TYPE_MOBILE_EMERGENCY = 15;
563
Hui Lu1c5624a2014-01-15 11:05:36 -0500564 /**
565 * The network that uses proxy to achieve connectivity.
566 * {@hide}
567 */
568 public static final int TYPE_PROXY = 16;
Wink Saville5e56bc52013-07-29 15:00:57 -0700569
Robert Greenwalt8283f882014-07-07 17:09:01 -0700570 /**
571 * A virtual network using one or more native bearers.
572 * It may or may not be providing security services.
573 */
574 public static final int TYPE_VPN = 17;
Hui Lu1c5624a2014-01-15 11:05:36 -0500575
576 /** {@hide} */
Robert Greenwalt8283f882014-07-07 17:09:01 -0700577 public static final int MAX_RADIO_TYPE = TYPE_VPN;
578
579 /** {@hide} */
580 public static final int MAX_NETWORK_TYPE = TYPE_VPN;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800581
Jianzheng Zhoudcf03f32012-11-16 13:45:20 +0800582 /**
583 * If you want to set the default network preference,you can directly
584 * change the networkAttributes array in framework's config.xml.
585 *
586 * @deprecated Since we support so many more networks now, the single
587 * network default network preference can't really express
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800588 * the hierarchy. Instead, the default is defined by the
Jianzheng Zhoudcf03f32012-11-16 13:45:20 +0800589 * networkAttributes in config.xml. You can determine
Robert Greenwalt4c8b7482012-12-07 09:56:50 -0800590 * the current value by calling {@link #getNetworkPreference()}
Jianzheng Zhoudcf03f32012-11-16 13:45:20 +0800591 * from an App.
592 */
593 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800594 public static final int DEFAULT_NETWORK_PREFERENCE = TYPE_WIFI;
595
Jeff Sharkey625239a2012-09-26 22:03:49 -0700596 /**
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700597 * @hide
598 */
Hugo Benichia5c1f7f2017-06-20 14:10:14 +0900599 public static final int REQUEST_ID_UNSET = 0;
Robert Greenwalt7569f182014-06-08 16:42:59 -0700600
Paul Jensen5d59e782014-07-11 12:28:19 -0400601 /**
Hugo Benichi31c176d2017-06-17 13:14:12 +0900602 * Static unique request used as a tombstone for NetworkCallbacks that have been unregistered.
603 * This allows to distinguish when unregistering NetworkCallbacks those that were never
604 * registered and those that were already unregistered.
605 * @hide
606 */
Hugo Benichia5c1f7f2017-06-20 14:10:14 +0900607 private static final NetworkRequest ALREADY_UNREGISTERED =
Hugo Benichi31c176d2017-06-17 13:14:12 +0900608 new NetworkRequest.Builder().clearCapabilities().build();
609
610 /**
Paul Jensen5d59e782014-07-11 12:28:19 -0400611 * A NetID indicating no Network is selected.
612 * Keep in sync with bionic/libc/dns/include/resolv_netid.h
613 * @hide
614 */
615 public static final int NETID_UNSET = 0;
616
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700617 private final IConnectivityManager mService;
Paul Jensene0bef712014-12-10 15:12:18 -0500618 /**
619 * A kludge to facilitate static access where a Context pointer isn't available, like in the
620 * case of the static set/getProcessDefaultNetwork methods and from the Network class.
621 * TODO: Remove this after deprecating the static methods in favor of non-static methods or
622 * methods that take a Context argument.
623 */
624 private static ConnectivityManager sInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800625
Lorenzo Colittiffc42b02015-07-29 11:41:21 +0900626 private final Context mContext;
627
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800628 private INetworkManagementService mNMService;
Felipe Leme1b103232016-01-22 09:44:57 -0800629 private INetworkPolicyManager mNPManager;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800630
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800631 /**
632 * Tests if a given integer represents a valid network type.
633 * @param networkType the type to be tested
634 * @return a boolean. {@code true} if the type is valid, else {@code false}
Paul Jensen9e59e122015-05-06 10:42:25 -0400635 * @deprecated All APIs accepting a network type are deprecated. There should be no need to
636 * validate a network type.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800637 */
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700638 public static boolean isNetworkTypeValid(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700639 return networkType >= 0 && networkType <= MAX_NETWORK_TYPE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800640 }
641
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800642 /**
643 * Returns a non-localized string representing a given network type.
644 * ONLY used for debugging output.
645 * @param type the type needing naming
646 * @return a String for the given type, or a string version of the type ("87")
647 * if no name is known.
648 * {@hide}
649 */
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700650 public static String getNetworkTypeName(int type) {
651 switch (type) {
652 case TYPE_MOBILE:
653 return "MOBILE";
654 case TYPE_WIFI:
655 return "WIFI";
656 case TYPE_MOBILE_MMS:
657 return "MOBILE_MMS";
658 case TYPE_MOBILE_SUPL:
659 return "MOBILE_SUPL";
660 case TYPE_MOBILE_DUN:
661 return "MOBILE_DUN";
662 case TYPE_MOBILE_HIPRI:
663 return "MOBILE_HIPRI";
664 case TYPE_WIMAX:
665 return "WIMAX";
666 case TYPE_BLUETOOTH:
667 return "BLUETOOTH";
668 case TYPE_DUMMY:
669 return "DUMMY";
670 case TYPE_ETHERNET:
671 return "ETHERNET";
672 case TYPE_MOBILE_FOTA:
673 return "MOBILE_FOTA";
674 case TYPE_MOBILE_IMS:
675 return "MOBILE_IMS";
676 case TYPE_MOBILE_CBS:
677 return "MOBILE_CBS";
repo syncaea743a2011-07-29 23:55:49 -0700678 case TYPE_WIFI_P2P:
679 return "WIFI_P2P";
Wink Saville5e56bc52013-07-29 15:00:57 -0700680 case TYPE_MOBILE_IA:
681 return "MOBILE_IA";
Ram3e0e3bc2014-06-26 11:03:44 -0700682 case TYPE_MOBILE_EMERGENCY:
683 return "MOBILE_EMERGENCY";
Hui Lu1c5624a2014-01-15 11:05:36 -0500684 case TYPE_PROXY:
685 return "PROXY";
Erik Kline37fbfa12014-11-19 17:23:41 +0900686 case TYPE_VPN:
687 return "VPN";
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700688 default:
689 return Integer.toString(type);
690 }
691 }
692
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800693 /**
694 * Checks if a given type uses the cellular data connection.
695 * This should be replaced in the future by a network property.
696 * @param networkType the type to check
697 * @return a boolean - {@code true} if uses cellular network, else {@code false}
698 * {@hide}
699 */
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700700 public static boolean isNetworkTypeMobile(int networkType) {
701 switch (networkType) {
702 case TYPE_MOBILE:
703 case TYPE_MOBILE_MMS:
704 case TYPE_MOBILE_SUPL:
705 case TYPE_MOBILE_DUN:
706 case TYPE_MOBILE_HIPRI:
707 case TYPE_MOBILE_FOTA:
708 case TYPE_MOBILE_IMS:
709 case TYPE_MOBILE_CBS:
Wink Saville5e56bc52013-07-29 15:00:57 -0700710 case TYPE_MOBILE_IA:
Ram3e0e3bc2014-06-26 11:03:44 -0700711 case TYPE_MOBILE_EMERGENCY:
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700712 return true;
713 default:
714 return false;
715 }
716 }
717
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800718 /**
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700719 * Checks if the given network type is backed by a Wi-Fi radio.
720 *
721 * @hide
722 */
723 public static boolean isNetworkTypeWifi(int networkType) {
724 switch (networkType) {
725 case TYPE_WIFI:
726 case TYPE_WIFI_P2P:
727 return true;
728 default:
729 return false;
730 }
731 }
732
733 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800734 * Specifies the preferred network type. When the device has more
735 * than one type available the preferred network type will be used.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800736 *
737 * @param preference the network type to prefer over all others. It is
738 * unspecified what happens to the old preferred network in the
739 * overall ordering.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -0700740 * @deprecated Functionality has been removed as it no longer makes sense,
741 * with many more than two networks - we'd need an array to express
742 * preference. Instead we use dynamic network properties of
743 * the networks to describe their precedence.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800744 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800745 public void setNetworkPreference(int preference) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800746 }
747
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800748 /**
749 * Retrieves the current preferred network type.
Paul Jensenb2748922015-05-06 11:10:18 -0400750 * <p>This method requires the caller to hold the permission
751 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800752 *
753 * @return an integer representing the preferred network type
754 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -0700755 * @deprecated Functionality has been removed as it no longer makes sense,
756 * with many more than two networks - we'd need an array to express
757 * preference. Instead we use dynamic network properties of
758 * the networks to describe their precedence.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800759 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800760 public int getNetworkPreference() {
Robert Greenwaltd19c41c2014-05-18 23:07:25 -0700761 return TYPE_NONE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800762 }
763
Scott Main671644c2011-10-06 19:02:28 -0700764 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800765 * Returns details about the currently active default data network. When
766 * connected, this network is the default route for outgoing connections.
767 * You should always check {@link NetworkInfo#isConnected()} before initiating
768 * network traffic. This may return {@code null} when there is no default
769 * network.
Paul Jensenb2748922015-05-06 11:10:18 -0400770 * <p>This method requires the caller to hold the permission
771 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800772 *
773 * @return a {@link NetworkInfo} object for the current default network
Paul Jensen0d719ca2015-02-13 14:18:39 -0500774 * or {@code null} if no default network is currently active
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -0700775 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800776 public NetworkInfo getActiveNetworkInfo() {
777 try {
778 return mService.getActiveNetworkInfo();
779 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -0700780 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800781 }
782 }
783
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800784 /**
Paul Jensen31a94f42015-02-13 14:18:39 -0500785 * Returns a {@link Network} object corresponding to the currently active
786 * default data network. In the event that the current active default data
787 * network disconnects, the returned {@code Network} object will no longer
788 * be usable. This will return {@code null} when there is no default
789 * network.
Paul Jensenb2748922015-05-06 11:10:18 -0400790 * <p>This method requires the caller to hold the permission
791 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Paul Jensen31a94f42015-02-13 14:18:39 -0500792 *
793 * @return a {@link Network} object for the current default network or
794 * {@code null} if no default network is currently active
Paul Jensen31a94f42015-02-13 14:18:39 -0500795 */
796 public Network getActiveNetwork() {
797 try {
798 return mService.getActiveNetwork();
799 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -0700800 throw e.rethrowFromSystemServer();
Paul Jensen31a94f42015-02-13 14:18:39 -0500801 }
802 }
803
804 /**
Robin Leed2baf792016-03-24 12:07:00 +0000805 * Returns a {@link Network} object corresponding to the currently active
806 * default data network for a specific UID. In the event that the default data
807 * network disconnects, the returned {@code Network} object will no longer
808 * be usable. This will return {@code null} when there is no default
809 * network for the UID.
810 * <p>This method requires the caller to hold the permission
811 * {@link android.Manifest.permission#CONNECTIVITY_INTERNAL}.
812 *
813 * @return a {@link Network} object for the current default network for the
814 * given UID or {@code null} if no default network is currently active
815 *
816 * @hide
817 */
818 public Network getActiveNetworkForUid(int uid) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600819 return getActiveNetworkForUid(uid, false);
820 }
821
822 /** {@hide} */
823 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +0000824 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600825 return mService.getActiveNetworkForUid(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +0000826 } catch (RemoteException e) {
827 throw e.rethrowFromSystemServer();
828 }
829 }
830
831 /**
Robin Lee244ce8e2016-01-05 18:03:46 +0000832 * Configures an always-on VPN connection through a specific application.
833 * This connection is automatically granted and persisted after a reboot.
834 *
835 * <p>The designated package should declare a {@link VpnService} in its
836 * manifest guarded by {@link android.Manifest.permission.BIND_VPN_SERVICE},
837 * otherwise the call will fail.
838 *
839 * @param userId The identifier of the user to set an always-on VPN for.
840 * @param vpnPackage The package name for an installed VPN app on the device, or {@code null}
841 * to remove an existing always-on VPN configuration.
Robin Leedc679712016-05-03 13:23:03 +0100842 * @param lockdownEnabled {@code true} to disallow networking when the VPN is not connected or
843 * {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +0000844 * @return {@code true} if the package is set as always-on VPN controller;
845 * {@code false} otherwise.
846 * @hide
847 */
Robin Leedc679712016-05-03 13:23:03 +0100848 public boolean setAlwaysOnVpnPackageForUser(int userId, @Nullable String vpnPackage,
849 boolean lockdownEnabled) {
Robin Lee244ce8e2016-01-05 18:03:46 +0000850 try {
Robin Leedc679712016-05-03 13:23:03 +0100851 return mService.setAlwaysOnVpnPackage(userId, vpnPackage, lockdownEnabled);
Robin Lee244ce8e2016-01-05 18:03:46 +0000852 } 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 /**
858 * Returns the package name of the currently set always-on VPN application.
859 * If there is no always-on VPN set, or the VPN is provided by the system instead
860 * of by an app, {@code null} will be returned.
861 *
862 * @return Package name of VPN controller responsible for always-on VPN,
863 * or {@code null} if none is set.
864 * @hide
865 */
866 public String getAlwaysOnVpnPackageForUser(int userId) {
867 try {
868 return mService.getAlwaysOnVpnPackage(userId);
869 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -0700870 throw e.rethrowFromSystemServer();
Robin Lee244ce8e2016-01-05 18:03:46 +0000871 }
872 }
873
874 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800875 * Returns details about the currently active default data network
876 * for a given uid. This is for internal use only to avoid spying
877 * other apps.
Paul Jensenb2748922015-05-06 11:10:18 -0400878 * <p>This method requires the caller to hold the permission
879 * {@link android.Manifest.permission#CONNECTIVITY_INTERNAL}
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800880 *
881 * @return a {@link NetworkInfo} object for the current default network
882 * for the given uid or {@code null} if no default network is
883 * available for the specified uid.
884 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800885 * {@hide}
886 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700887 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600888 return getActiveNetworkInfoForUid(uid, false);
889 }
890
891 /** {@hide} */
892 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700893 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600894 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700895 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -0700896 throw e.rethrowFromSystemServer();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700897 }
898 }
899
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800900 /**
901 * Returns connection status information about a particular
902 * network type.
Paul Jensenb2748922015-05-06 11:10:18 -0400903 * <p>This method requires the caller to hold the permission
904 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800905 *
906 * @param networkType integer specifying which networkType in
907 * which you're interested.
908 * @return a {@link NetworkInfo} object for the requested
909 * network type or {@code null} if the type is not
910 * supported by the device.
911 *
Paul Jensen3541e9f2015-03-18 12:23:02 -0400912 * @deprecated This method does not support multiple connected networks
913 * of the same type. Use {@link #getAllNetworks} and
914 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800915 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800916 public NetworkInfo getNetworkInfo(int networkType) {
917 try {
918 return mService.getNetworkInfo(networkType);
919 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -0700920 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800921 }
922 }
923
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800924 /**
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -0700925 * Returns connection status information about a particular
926 * Network.
Paul Jensenb2748922015-05-06 11:10:18 -0400927 * <p>This method requires the caller to hold the permission
928 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -0700929 *
930 * @param network {@link Network} specifying which network
931 * in which you're interested.
932 * @return a {@link NetworkInfo} object for the requested
933 * network or {@code null} if the {@code Network}
934 * is not valid.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -0700935 */
936 public NetworkInfo getNetworkInfo(Network network) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600937 return getNetworkInfoForUid(network, Process.myUid(), false);
938 }
939
940 /** {@hide} */
941 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -0700942 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600943 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -0700944 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -0700945 throw e.rethrowFromSystemServer();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -0700946 }
947 }
948
949 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800950 * Returns connection status information about all network
951 * types supported by the device.
Paul Jensenb2748922015-05-06 11:10:18 -0400952 * <p>This method requires the caller to hold the permission
953 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800954 *
955 * @return an array of {@link NetworkInfo} objects. Check each
956 * {@link NetworkInfo#getType} for which type each applies.
957 *
Paul Jensen3541e9f2015-03-18 12:23:02 -0400958 * @deprecated This method does not support multiple connected networks
959 * of the same type. Use {@link #getAllNetworks} and
960 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800961 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800962 public NetworkInfo[] getAllNetworkInfo() {
963 try {
964 return mService.getAllNetworkInfo();
965 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -0700966 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800967 }
968 }
969
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800970 /**
Lorenzo Colittib57edc52014-08-22 17:10:50 -0700971 * Returns the {@link Network} object currently serving a given type, or
972 * null if the given type is not connected.
973 *
974 * <p>This method requires the caller to hold the permission
975 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
976 *
977 * @hide
Paul Jensen3541e9f2015-03-18 12:23:02 -0400978 * @deprecated This method does not support multiple connected networks
979 * of the same type. Use {@link #getAllNetworks} and
980 * {@link #getNetworkInfo(android.net.Network)} instead.
Lorenzo Colittib57edc52014-08-22 17:10:50 -0700981 */
982 public Network getNetworkForType(int networkType) {
983 try {
984 return mService.getNetworkForType(networkType);
985 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -0700986 throw e.rethrowFromSystemServer();
Lorenzo Colittib57edc52014-08-22 17:10:50 -0700987 }
988 }
989
990 /**
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -0700991 * Returns an array of all {@link Network} currently tracked by the
992 * framework.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -0700993 * <p>This method requires the caller to hold the permission
994 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Paul Jensenb2748922015-05-06 11:10:18 -0400995 *
996 * @return an array of {@link Network} objects.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -0700997 */
998 public Network[] getAllNetworks() {
999 try {
1000 return mService.getAllNetworks();
1001 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001002 throw e.rethrowFromSystemServer();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001003 }
1004 }
1005
1006 /**
Lorenzo Colittie285b432015-04-23 15:32:42 +09001007 * Returns an array of {@link android.net.NetworkCapabilities} objects, representing
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001008 * the Networks that applications run by the given user will use by default.
1009 * @hide
1010 */
1011 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1012 try {
1013 return mService.getDefaultNetworkCapabilitiesForUser(userId);
1014 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001015 throw e.rethrowFromSystemServer();
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001016 }
1017 }
1018
1019 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001020 * Returns the IP information for the current default network.
Paul Jensenb2748922015-05-06 11:10:18 -04001021 * <p>This method requires the caller to hold the permission
1022 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001023 *
1024 * @return a {@link LinkProperties} object describing the IP info
1025 * for the current default network, or {@code null} if there
1026 * is no current default network.
1027 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001028 * {@hide}
1029 */
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001030 public LinkProperties getActiveLinkProperties() {
1031 try {
1032 return mService.getActiveLinkProperties();
1033 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001034 throw e.rethrowFromSystemServer();
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001035 }
1036 }
1037
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001038 /**
1039 * Returns the IP information for a given network type.
Paul Jensenb2748922015-05-06 11:10:18 -04001040 * <p>This method requires the caller to hold the permission
1041 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001042 *
1043 * @param networkType the network type of interest.
1044 * @return a {@link LinkProperties} object describing the IP info
1045 * for the given networkType, or {@code null} if there is
1046 * no current default network.
1047 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001048 * {@hide}
Paul Jensen3541e9f2015-03-18 12:23:02 -04001049 * @deprecated This method does not support multiple connected networks
1050 * of the same type. Use {@link #getAllNetworks},
1051 * {@link #getNetworkInfo(android.net.Network)}, and
1052 * {@link #getLinkProperties(android.net.Network)} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001053 */
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001054 public LinkProperties getLinkProperties(int networkType) {
1055 try {
Robert Greenwalt9258c642014-03-26 16:47:06 -07001056 return mService.getLinkPropertiesForType(networkType);
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 /**
1063 * Get the {@link LinkProperties} for the given {@link Network}. This
1064 * 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.
1069 * @return The {@link LinkProperties} for the network, or {@code null}.
Paul Jensenb2748922015-05-06 11:10:18 -04001070 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07001071 public LinkProperties getLinkProperties(Network network) {
1072 try {
1073 return mService.getLinkProperties(network);
1074 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001075 throw e.rethrowFromSystemServer();
Robert Greenwalt9258c642014-03-26 16:47:06 -07001076 }
1077 }
1078
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001079 /**
Lorenzo Colittie285b432015-04-23 15:32:42 +09001080 * Get the {@link android.net.NetworkCapabilities} for the given {@link Network}. This
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001081 * will return {@code null} if the network is unknown.
Paul Jensenb2748922015-05-06 11:10:18 -04001082 * <p>This method requires the caller to hold the permission
1083 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001084 *
1085 * @param network The {@link Network} object identifying the network in question.
Lorenzo Colittie285b432015-04-23 15:32:42 +09001086 * @return The {@link android.net.NetworkCapabilities} for the network, or {@code null}.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001087 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07001088 public NetworkCapabilities getNetworkCapabilities(Network network) {
1089 try {
1090 return mService.getNetworkCapabilities(network);
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001091 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001092 throw e.rethrowFromSystemServer();
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001093 }
1094 }
1095
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001096 /**
Udam Sainib7c24872016-01-04 12:16:14 -08001097 * Gets the URL that should be used for resolving whether a captive portal is present.
1098 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1099 * portal is present.
1100 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1101 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1102 *
1103 * @hide
1104 */
1105 @SystemApi
1106 public String getCaptivePortalServerUrl() {
1107 try {
1108 return mService.getCaptivePortalServerUrl();
1109 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001110 throw e.rethrowFromSystemServer();
Udam Sainib7c24872016-01-04 12:16:14 -08001111 }
1112 }
1113
1114 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001115 * Tells the underlying networking system that the caller wants to
1116 * begin using the named feature. The interpretation of {@code feature}
1117 * is completely up to each networking implementation.
Lorenzo Colittid5427052015-10-15 16:29:00 +09001118 *
1119 * <p>This method requires the caller to hold either the
1120 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1121 * or the ability to modify system settings as determined by
1122 * {@link android.provider.Settings.System#canWrite}.</p>
1123 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001124 * @param networkType specifies which network the request pertains to
1125 * @param feature the name of the feature to be used
1126 * @return an integer value representing the outcome of the request.
1127 * The interpretation of this value is specific to each networking
1128 * implementation+feature combination, except that the value {@code -1}
1129 * always indicates failure.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001130 *
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +09001131 * @deprecated Deprecated in favor of the cleaner
1132 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
Dianne Hackborn692a2442015-07-31 10:35:34 -07001133 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001134 * throw {@code UnsupportedOperationException} if called.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001135 */
1136 public int startUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001137 checkLegacyRoutingApiAccess();
Robert Greenwalt562cc542014-05-15 18:07:26 -07001138 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1139 if (netCap == null) {
1140 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1141 feature);
1142 return PhoneConstants.APN_REQUEST_FAILED;
1143 }
1144
1145 NetworkRequest request = null;
1146 synchronized (sLegacyRequests) {
1147 LegacyRequest l = sLegacyRequests.get(netCap);
1148 if (l != null) {
1149 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1150 renewRequestLocked(l);
1151 if (l.currentNetwork != null) {
1152 return PhoneConstants.APN_ALREADY_ACTIVE;
1153 } else {
1154 return PhoneConstants.APN_REQUEST_STARTED;
1155 }
1156 }
1157
1158 request = requestNetworkForFeatureLocked(netCap);
1159 }
1160 if (request != null) {
Robert Greenwalt257ee5f2014-06-20 10:58:45 -07001161 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001162 return PhoneConstants.APN_REQUEST_STARTED;
1163 } else {
1164 Log.d(TAG, " request Failed");
1165 return PhoneConstants.APN_REQUEST_FAILED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001166 }
1167 }
1168
1169 /**
1170 * Tells the underlying networking system that the caller is finished
1171 * using the named feature. The interpretation of {@code feature}
1172 * is completely up to each networking implementation.
Lorenzo Colittid5427052015-10-15 16:29:00 +09001173 *
1174 * <p>This method requires the caller to hold either the
1175 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1176 * or the ability to modify system settings as determined by
1177 * {@link android.provider.Settings.System#canWrite}.</p>
1178 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001179 * @param networkType specifies which network the request pertains to
1180 * @param feature the name of the feature that is no longer needed
1181 * @return an integer value representing the outcome of the request.
1182 * The interpretation of this value is specific to each networking
1183 * implementation+feature combination, except that the value {@code -1}
1184 * always indicates failure.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001185 *
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09001186 * @deprecated Deprecated in favor of the cleaner
1187 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
Dianne Hackborn692a2442015-07-31 10:35:34 -07001188 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001189 * throw {@code UnsupportedOperationException} if called.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001190 */
1191 public int stopUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001192 checkLegacyRoutingApiAccess();
Robert Greenwalt562cc542014-05-15 18:07:26 -07001193 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1194 if (netCap == null) {
1195 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
1196 feature);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001197 return -1;
1198 }
Robert Greenwalt562cc542014-05-15 18:07:26 -07001199
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001200 if (removeRequestForFeature(netCap)) {
Robert Greenwalt562cc542014-05-15 18:07:26 -07001201 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001202 }
1203 return 1;
1204 }
1205
1206 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
1207 if (networkType == TYPE_MOBILE) {
Erik Kline35bf06c2017-01-26 18:08:28 +09001208 switch (feature) {
1209 case "enableCBS":
1210 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
1211 case "enableDUN":
1212 case "enableDUNAlways":
1213 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
1214 case "enableFOTA":
1215 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
1216 case "enableHIPRI":
1217 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
1218 case "enableIMS":
1219 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
1220 case "enableMMS":
1221 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
1222 case "enableSUPL":
1223 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
1224 default:
1225 return null;
Robert Greenwalt562cc542014-05-15 18:07:26 -07001226 }
Erik Kline35bf06c2017-01-26 18:08:28 +09001227 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
1228 return networkCapabilitiesForType(TYPE_WIFI_P2P);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001229 }
1230 return null;
1231 }
1232
Robert Greenwalt06314e42014-10-29 14:04:06 -07001233 /**
1234 * Guess what the network request was trying to say so that the resulting
1235 * network is accessible via the legacy (deprecated) API such as
1236 * requestRouteToHost.
Lorenzo Colittidef4cb02015-11-25 20:28:50 +09001237 *
1238 * This means we should try to be fairly precise about transport and
Robert Greenwalt06314e42014-10-29 14:04:06 -07001239 * capability but ignore things such as networkSpecifier.
1240 * If the request has more than one transport or capability it doesn't
1241 * match the old legacy requests (they selected only single transport/capability)
1242 * so this function cannot map the request to a single legacy type and
1243 * the resulting network will not be available to the legacy APIs.
1244 *
Lorenzo Colittidef4cb02015-11-25 20:28:50 +09001245 * This code is only called from the requestNetwork API (L and above).
1246 *
1247 * Setting a legacy type causes CONNECTIVITY_ACTION broadcasts, which are expensive
1248 * because they wake up lots of apps - see http://b/23350688 . So we currently only
1249 * do this for SUPL requests, which are the only ones that we know need it. If
1250 * omitting these broadcasts causes unacceptable app breakage, then for backwards
1251 * compatibility we can send them:
1252 *
1253 * if (targetSdkVersion < Build.VERSION_CODES.M) && // legacy API unsupported >= M
1254 * targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP)) // requestNetwork not present < L
1255 *
Robert Greenwalt06314e42014-10-29 14:04:06 -07001256 * TODO - This should be removed when the legacy APIs are removed.
1257 */
Ye Wenb87875e2014-07-21 14:19:01 -07001258 private int inferLegacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
1259 if (netCap == null) {
1260 return TYPE_NONE;
1261 }
Robert Greenwalt06314e42014-10-29 14:04:06 -07001262
Ye Wenb87875e2014-07-21 14:19:01 -07001263 if (!netCap.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
1264 return TYPE_NONE;
1265 }
Robert Greenwalt06314e42014-10-29 14:04:06 -07001266
Lifu Tang30f95a72016-01-07 23:20:38 -08001267 // Do this only for SUPL, until GnssLocationProvider is fixed. http://b/25876485 .
Lorenzo Colittidef4cb02015-11-25 20:28:50 +09001268 if (!netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1269 // NOTE: if this causes app breakage, we should not just comment out this early return;
1270 // instead, we should make this early return conditional on the requesting app's target
1271 // SDK version, as described in the comment above.
1272 return TYPE_NONE;
1273 }
1274
Robert Greenwalt06314e42014-10-29 14:04:06 -07001275 String type = null;
1276 int result = TYPE_NONE;
1277
Ye Wenb87875e2014-07-21 14:19:01 -07001278 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
Robert Greenwalt06314e42014-10-29 14:04:06 -07001279 type = "enableCBS";
1280 result = TYPE_MOBILE_CBS;
1281 } else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1282 type = "enableIMS";
1283 result = TYPE_MOBILE_IMS;
1284 } else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1285 type = "enableFOTA";
1286 result = TYPE_MOBILE_FOTA;
1287 } else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1288 type = "enableDUN";
1289 result = TYPE_MOBILE_DUN;
1290 } else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
Lorenzo Colittidef4cb02015-11-25 20:28:50 +09001291 type = "enableSUPL";
Robert Greenwalt06314e42014-10-29 14:04:06 -07001292 result = TYPE_MOBILE_SUPL;
Robert Greenwalt74ab4fa2015-08-28 12:37:54 -07001293 // back out this hack for mms as they no longer need this and it's causing
1294 // device slowdowns - b/23350688 (note, supl still needs this)
1295 //} else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1296 // type = "enableMMS";
1297 // result = TYPE_MOBILE_MMS;
Robert Greenwalt06314e42014-10-29 14:04:06 -07001298 } else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1299 type = "enableHIPRI";
1300 result = TYPE_MOBILE_HIPRI;
Ye Wenb87875e2014-07-21 14:19:01 -07001301 }
Robert Greenwalt06314e42014-10-29 14:04:06 -07001302 if (type != null) {
1303 NetworkCapabilities testCap = networkCapabilitiesForFeature(TYPE_MOBILE, type);
1304 if (testCap.equalsNetCapabilities(netCap) && testCap.equalsTransportTypes(netCap)) {
1305 return result;
Ye Wenb87875e2014-07-21 14:19:01 -07001306 }
1307 }
1308 return TYPE_NONE;
1309 }
1310
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07001311 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
Robert Greenwalt562cc542014-05-15 18:07:26 -07001312 if (netCap == null) return TYPE_NONE;
1313 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
1314 return TYPE_MOBILE_CBS;
1315 }
1316 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1317 return TYPE_MOBILE_IMS;
1318 }
1319 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1320 return TYPE_MOBILE_FOTA;
1321 }
1322 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1323 return TYPE_MOBILE_DUN;
1324 }
1325 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1326 return TYPE_MOBILE_SUPL;
1327 }
1328 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1329 return TYPE_MOBILE_MMS;
1330 }
1331 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1332 return TYPE_MOBILE_HIPRI;
1333 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07001334 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
1335 return TYPE_WIFI_P2P;
1336 }
Robert Greenwalt562cc542014-05-15 18:07:26 -07001337 return TYPE_NONE;
1338 }
1339
1340 private static class LegacyRequest {
1341 NetworkCapabilities networkCapabilities;
1342 NetworkRequest networkRequest;
1343 int expireSequenceNumber;
1344 Network currentNetwork;
1345 int delay = -1;
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001346
1347 private void clearDnsBinding() {
1348 if (currentNetwork != null) {
1349 currentNetwork = null;
1350 setProcessDefaultNetworkForHostResolution(null);
1351 }
1352 }
1353
Robert Greenwalt6078b502014-06-11 16:05:07 -07001354 NetworkCallback networkCallback = new NetworkCallback() {
Robert Greenwalt562cc542014-05-15 18:07:26 -07001355 @Override
Robert Greenwalt6078b502014-06-11 16:05:07 -07001356 public void onAvailable(Network network) {
Robert Greenwalt562cc542014-05-15 18:07:26 -07001357 currentNetwork = network;
1358 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04001359 setProcessDefaultNetworkForHostResolution(network);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001360 }
1361 @Override
Robert Greenwalt6078b502014-06-11 16:05:07 -07001362 public void onLost(Network network) {
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001363 if (network.equals(currentNetwork)) clearDnsBinding();
Robert Greenwalt562cc542014-05-15 18:07:26 -07001364 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
1365 }
1366 };
1367 }
1368
Robert Greenwaltfab501672014-07-23 11:44:01 -07001369 private static HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
Robert Greenwalt562cc542014-05-15 18:07:26 -07001370 new HashMap<NetworkCapabilities, LegacyRequest>();
1371
1372 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
1373 synchronized (sLegacyRequests) {
1374 LegacyRequest l = sLegacyRequests.get(netCap);
1375 if (l != null) return l.networkRequest;
1376 }
1377 return null;
1378 }
1379
1380 private void renewRequestLocked(LegacyRequest l) {
1381 l.expireSequenceNumber++;
1382 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
1383 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
1384 }
1385
1386 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
1387 int ourSeqNum = -1;
1388 synchronized (sLegacyRequests) {
1389 LegacyRequest l = sLegacyRequests.get(netCap);
1390 if (l == null) return;
1391 ourSeqNum = l.expireSequenceNumber;
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001392 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001393 }
1394 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
1395 }
1396
1397 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
1398 int delay = -1;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07001399 int type = legacyTypeForNetworkCapabilities(netCap);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001400 try {
1401 delay = mService.getRestoreDefaultNetworkDelay(type);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001402 } catch (RemoteException e) {
1403 throw e.rethrowFromSystemServer();
1404 }
Robert Greenwalt562cc542014-05-15 18:07:26 -07001405 LegacyRequest l = new LegacyRequest();
1406 l.networkCapabilities = netCap;
1407 l.delay = delay;
1408 l.expireSequenceNumber = 0;
Hugo Benichi2583ef02017-02-02 17:02:36 +09001409 l.networkRequest = sendRequestForNetwork(
1410 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
Robert Greenwalt562cc542014-05-15 18:07:26 -07001411 if (l.networkRequest == null) return null;
1412 sLegacyRequests.put(netCap, l);
1413 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
1414 return l.networkRequest;
1415 }
1416
1417 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
1418 if (delay >= 0) {
1419 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
Hugo Benichi2583ef02017-02-02 17:02:36 +09001420 CallbackHandler handler = getDefaultHandler();
Hugo Benichi6f260f32017-02-03 14:18:44 +09001421 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
1422 handler.sendMessageDelayed(msg, delay);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001423 }
1424 }
1425
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001426 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
1427 final LegacyRequest l;
Robert Greenwalt562cc542014-05-15 18:07:26 -07001428 synchronized (sLegacyRequests) {
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001429 l = sLegacyRequests.remove(netCap);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001430 }
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001431 if (l == null) return false;
1432 unregisterNetworkCallback(l.networkCallback);
1433 l.clearDnsBinding();
1434 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001435 }
1436
Erik Kline35bf06c2017-01-26 18:08:28 +09001437 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
1438 static {
1439 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
1440 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
1441 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
1442 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
1443 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
1444 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1445 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1446 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
1447 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
1448 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
1449 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
1450 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
1451 }
1452
1453 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
1454 static {
1455 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
1456 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
1457 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
1458 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
1459 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
1460 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
1461 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
1462 }
1463
1464 /**
1465 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
1466 * instance suitable for registering a request or callback. Throws an
1467 * IllegalArgumentException if no mapping from the legacy type to
1468 * NetworkCapabilities is known.
1469 *
1470 * @hide
1471 */
1472 public static NetworkCapabilities networkCapabilitiesForType(int type) {
1473 final NetworkCapabilities nc = new NetworkCapabilities();
1474
1475 // Map from type to transports.
1476 final int NOT_FOUND = -1;
1477 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
Hugo Benichie7678512017-05-09 15:19:01 +09001478 Preconditions.checkArgument(transport != NOT_FOUND, "unknown legacy type: " + type);
Erik Kline35bf06c2017-01-26 18:08:28 +09001479 nc.addTransportType(transport);
1480
1481 // Map from type to capabilities.
1482 nc.addCapability(sLegacyTypeToCapability.get(
1483 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
1484 nc.maybeMarkCapabilitiesRestricted();
1485 return nc;
1486 }
1487
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001488 /** @hide */
1489 public static class PacketKeepaliveCallback {
1490 /** The requested keepalive was successfully started. */
1491 public void onStarted() {}
1492 /** The keepalive was successfully stopped. */
1493 public void onStopped() {}
1494 /** An error occurred. */
1495 public void onError(int error) {}
1496 }
1497
1498 /**
1499 * Allows applications to request that the system periodically send specific packets on their
1500 * behalf, using hardware offload to save battery power.
1501 *
1502 * To request that the system send keepalives, call one of the methods that return a
1503 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
1504 * passing in a non-null callback. If the callback is successfully started, the callback's
1505 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
1506 * specifying one of the {@code ERROR_*} constants in this class.
1507 *
1508 * To stop an existing keepalive, call {@link stop}. The system will call {@code onStopped} if
1509 * the operation was successfull or {@code onError} if an error occurred.
1510 *
1511 * @hide
1512 */
1513 public class PacketKeepalive {
1514
1515 private static final String TAG = "PacketKeepalive";
1516
1517 /** @hide */
1518 public static final int SUCCESS = 0;
1519
1520 /** @hide */
1521 public static final int NO_KEEPALIVE = -1;
1522
1523 /** @hide */
1524 public static final int BINDER_DIED = -10;
1525
1526 /** The specified {@code Network} is not connected. */
1527 public static final int ERROR_INVALID_NETWORK = -20;
1528 /** The specified IP addresses are invalid. For example, the specified source IP address is
1529 * not configured on the specified {@code Network}. */
1530 public static final int ERROR_INVALID_IP_ADDRESS = -21;
1531 /** The requested port is invalid. */
1532 public static final int ERROR_INVALID_PORT = -22;
1533 /** The packet length is invalid (e.g., too long). */
1534 public static final int ERROR_INVALID_LENGTH = -23;
1535 /** The packet transmission interval is invalid (e.g., too short). */
1536 public static final int ERROR_INVALID_INTERVAL = -24;
1537
1538 /** The hardware does not support this request. */
1539 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
Lorenzo Colitti9d1284e2015-09-08 16:46:36 +09001540 /** The hardware returned an error. */
1541 public static final int ERROR_HARDWARE_ERROR = -31;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001542
1543 public static final int NATT_PORT = 4500;
1544
1545 private final Network mNetwork;
1546 private final PacketKeepaliveCallback mCallback;
1547 private final Looper mLooper;
1548 private final Messenger mMessenger;
1549
1550 private volatile Integer mSlot;
1551
1552 void stopLooper() {
1553 mLooper.quit();
1554 }
1555
1556 public void stop() {
1557 try {
1558 mService.stopKeepalive(mNetwork, mSlot);
1559 } catch (RemoteException e) {
1560 Log.e(TAG, "Error stopping packet keepalive: ", e);
1561 stopLooper();
1562 }
1563 }
1564
1565 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09001566 Preconditions.checkNotNull(network, "network cannot be null");
1567 Preconditions.checkNotNull(callback, "callback cannot be null");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001568 mNetwork = network;
1569 mCallback = callback;
1570 HandlerThread thread = new HandlerThread(TAG);
1571 thread.start();
1572 mLooper = thread.getLooper();
1573 mMessenger = new Messenger(new Handler(mLooper) {
1574 @Override
1575 public void handleMessage(Message message) {
1576 switch (message.what) {
1577 case NetworkAgent.EVENT_PACKET_KEEPALIVE:
1578 int error = message.arg2;
1579 try {
1580 if (error == SUCCESS) {
1581 if (mSlot == null) {
1582 mSlot = message.arg1;
1583 mCallback.onStarted();
1584 } else {
1585 mSlot = null;
1586 stopLooper();
1587 mCallback.onStopped();
1588 }
1589 } else {
1590 stopLooper();
1591 mCallback.onError(error);
1592 }
1593 } catch (Exception e) {
1594 Log.e(TAG, "Exception in keepalive callback(" + error + ")", e);
1595 }
1596 break;
1597 default:
1598 Log.e(TAG, "Unhandled message " + Integer.toHexString(message.what));
1599 break;
1600 }
1601 }
1602 });
1603 }
1604 }
1605
1606 /**
1607 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
1608 *
1609 * @hide
1610 */
1611 public PacketKeepalive startNattKeepalive(
1612 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
1613 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
1614 final PacketKeepalive k = new PacketKeepalive(network, callback);
1615 try {
1616 mService.startNattKeepalive(network, intervalSeconds, k.mMessenger, new Binder(),
1617 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
1618 } catch (RemoteException e) {
1619 Log.e(TAG, "Error starting packet keepalive: ", e);
1620 k.stopLooper();
1621 return null;
1622 }
1623 return k;
1624 }
1625
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001626 /**
1627 * Ensure that a network route exists to deliver traffic to the specified
1628 * host via the specified network interface. An attempt to add a route that
1629 * already exists is ignored, but treated as successful.
Lorenzo Colittid5427052015-10-15 16:29:00 +09001630 *
1631 * <p>This method requires the caller to hold either the
1632 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1633 * or the ability to modify system settings as determined by
1634 * {@link android.provider.Settings.System#canWrite}.</p>
1635 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001636 * @param networkType the type of the network over which traffic to the specified
1637 * host is to be routed
1638 * @param hostAddress the IP address of the host to which the route is desired
1639 * @return {@code true} on success, {@code false} on failure
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001640 *
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +09001641 * @deprecated Deprecated in favor of the
1642 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
1643 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
Dianne Hackborn692a2442015-07-31 10:35:34 -07001644 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001645 * throw {@code UnsupportedOperationException} if called.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001646 */
1647 public boolean requestRouteToHost(int networkType, int hostAddress) {
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001648 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001649 }
1650
1651 /**
1652 * Ensure that a network route exists to deliver traffic to the specified
1653 * host via the specified network interface. An attempt to add a route that
1654 * already exists is ignored, but treated as successful.
Lorenzo Colittid5427052015-10-15 16:29:00 +09001655 *
1656 * <p>This method requires the caller to hold either the
1657 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1658 * or the ability to modify system settings as determined by
1659 * {@link android.provider.Settings.System#canWrite}.</p>
1660 *
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001661 * @param networkType the type of the network over which traffic to the specified
1662 * host is to be routed
1663 * @param hostAddress the IP address of the host to which the route is desired
1664 * @return {@code true} on success, {@code false} on failure
1665 * @hide
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001666 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +09001667 * {@link #bindProcessToNetwork} API.
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001668 */
1669 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001670 checkLegacyRoutingApiAccess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001671 try {
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001672 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001673 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001674 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001675 }
1676 }
1677
1678 /**
1679 * Returns the value of the setting for background data usage. If false,
1680 * applications should not use the network if the application is not in the
1681 * foreground. Developers should respect this setting, and check the value
1682 * of this before performing any background data operations.
1683 * <p>
1684 * All applications that have background services that use the network
1685 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001686 * <p>
Scott Main4cc53332011-10-06 18:32:43 -07001687 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001688 * background data depends on several combined factors, and this method will
1689 * always return {@code true}. Instead, when background data is unavailable,
1690 * {@link #getActiveNetworkInfo()} will now appear disconnected.
Danica Chang6fdd0c62010-08-11 14:54:43 -07001691 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001692 * @return Whether background data usage is allowed.
1693 */
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001694 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001695 public boolean getBackgroundDataSetting() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001696 // assume that background data is allowed; final authority is
1697 // NetworkInfo which may be blocked.
1698 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001699 }
1700
1701 /**
1702 * Sets the value of the setting for background data usage.
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001703 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001704 * @param allowBackgroundData Whether an application should use data while
1705 * it is in the background.
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001706 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001707 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
1708 * @see #getBackgroundDataSetting()
1709 * @hide
1710 */
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001711 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001712 public void setBackgroundDataSetting(boolean allowBackgroundData) {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001713 // ignored
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001714 }
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001715
1716 /**
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001717 * Return quota status for the current active network, or {@code null} if no
1718 * network is active. Quota status can change rapidly, so these values
1719 * shouldn't be cached.
Jeff Sharkey44a3e0d2011-10-06 10:50:09 -07001720 *
Paul Jensen0d719ca2015-02-13 14:18:39 -05001721 * <p>This method requires the caller to hold the permission
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001722 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
1723 *
Jeff Sharkey44a3e0d2011-10-06 10:50:09 -07001724 * @hide
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001725 */
1726 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1727 try {
1728 return mService.getActiveNetworkQuotaInfo();
1729 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001730 throw e.rethrowFromSystemServer();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001731 }
1732 }
1733
1734 /**
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001735 * @hide
Robert Greenwaltafa05c02014-05-21 20:04:36 -07001736 * @deprecated Talk to TelephonyManager directly
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001737 */
1738 public boolean getMobileDataEnabled() {
Robert Greenwaltafa05c02014-05-21 20:04:36 -07001739 IBinder b = ServiceManager.getService(Context.TELEPHONY_SERVICE);
1740 if (b != null) {
1741 try {
1742 ITelephony it = ITelephony.Stub.asInterface(b);
Shishir Agrawal7ea3e8b2016-01-25 13:03:07 -08001743 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
Wink Saville36ffb042014-12-05 11:10:30 -08001744 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
1745 boolean retVal = it.getDataEnabled(subId);
1746 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
1747 + " retVal=" + retVal);
1748 return retVal;
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001749 } catch (RemoteException e) {
1750 throw e.rethrowFromSystemServer();
1751 }
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001752 }
Wink Saville36ffb042014-12-05 11:10:30 -08001753 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
Robert Greenwaltafa05c02014-05-21 20:04:36 -07001754 return false;
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001755 }
1756
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001757 /**
Robert Greenwaltb2489872014-09-04 16:44:35 -07001758 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
Robert Greenwalt6078b502014-06-11 16:05:07 -07001759 * to find out when the system default network has gone in to a high power state.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001760 */
1761 public interface OnNetworkActiveListener {
1762 /**
1763 * Called on the main thread of the process to report that the current data network
1764 * has become active, and it is now a good time to perform any pending network
1765 * operations. Note that this listener only tells you when the network becomes
1766 * active; if at any other time you want to know whether it is active (and thus okay
1767 * to initiate network traffic), you can retrieve its instantaneous state with
Robert Greenwalt6078b502014-06-11 16:05:07 -07001768 * {@link ConnectivityManager#isDefaultNetworkActive}.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001769 */
1770 public void onNetworkActive();
1771 }
1772
1773 private INetworkManagementService getNetworkManagementService() {
1774 synchronized (this) {
1775 if (mNMService != null) {
1776 return mNMService;
1777 }
1778 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
1779 mNMService = INetworkManagementService.Stub.asInterface(b);
1780 return mNMService;
1781 }
1782 }
1783
1784 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
1785 mNetworkActivityListeners
1786 = new ArrayMap<OnNetworkActiveListener, INetworkActivityListener>();
1787
1788 /**
Robert Greenwalt6078b502014-06-11 16:05:07 -07001789 * Start listening to reports when the system's default data network is active, meaning it is
1790 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
1791 * to determine the current state of the system's default network after registering the
1792 * listener.
1793 * <p>
1794 * If the process default network has been set with
Paul Jensen72db88e2015-03-10 10:54:12 -04001795 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
Robert Greenwalt6078b502014-06-11 16:05:07 -07001796 * reflect the process's default, but the system default.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001797 *
1798 * @param l The listener to be told when the network is active.
1799 */
Robert Greenwaltb2489872014-09-04 16:44:35 -07001800 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001801 INetworkActivityListener rl = new INetworkActivityListener.Stub() {
1802 @Override
1803 public void onNetworkActive() throws RemoteException {
1804 l.onNetworkActive();
1805 }
1806 };
1807
1808 try {
1809 getNetworkManagementService().registerNetworkActivityListener(rl);
1810 mNetworkActivityListeners.put(l, rl);
1811 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001812 throw e.rethrowFromSystemServer();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001813 }
1814 }
1815
1816 /**
1817 * Remove network active listener previously registered with
Robert Greenwaltb2489872014-09-04 16:44:35 -07001818 * {@link #addDefaultNetworkActiveListener}.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001819 *
1820 * @param l Previously registered listener.
1821 */
Robert Greenwaltb2489872014-09-04 16:44:35 -07001822 public void removeDefaultNetworkActiveListener(OnNetworkActiveListener l) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001823 INetworkActivityListener rl = mNetworkActivityListeners.get(l);
Hugo Benichie7678512017-05-09 15:19:01 +09001824 Preconditions.checkArgument(rl != null, "Listener was not registered.");
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001825 try {
1826 getNetworkManagementService().unregisterNetworkActivityListener(rl);
1827 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001828 throw e.rethrowFromSystemServer();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001829 }
1830 }
1831
1832 /**
1833 * Return whether the data network is currently active. An active network means that
1834 * it is currently in a high power state for performing data transmission. On some
1835 * types of networks, it may be expensive to move and stay in such a state, so it is
1836 * more power efficient to batch network traffic together when the radio is already in
1837 * this state. This method tells you whether right now is currently a good time to
1838 * initiate network traffic, as the network is already active.
1839 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07001840 public boolean isDefaultNetworkActive() {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001841 try {
1842 return getNetworkManagementService().isNetworkActive();
1843 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001844 throw e.rethrowFromSystemServer();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001845 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001846 }
1847
1848 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001849 * {@hide}
1850 */
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001851 public ConnectivityManager(Context context, IConnectivityManager service) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09001852 mContext = Preconditions.checkNotNull(context, "missing context");
1853 mService = Preconditions.checkNotNull(service, "missing IConnectivityManager");
Paul Jensene0bef712014-12-10 15:12:18 -05001854 sInstance = this;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001855 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001856
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001857 /** {@hide} */
1858 public static ConnectivityManager from(Context context) {
1859 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
1860 }
1861
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09001862 /* TODO: These permissions checks don't belong in client-side code. Move them to
1863 * services.jar, possibly in com.android.server.net. */
1864
1865 /** {@hide} */
1866 public static final boolean checkChangePermission(Context context) {
1867 int uid = Binder.getCallingUid();
1868 return Settings.checkAndNoteChangeNetworkStateOperation(context, uid, Settings
1869 .getPackageNameForUid(context, uid), false /* throwException */);
1870 }
1871
Lorenzo Colittid5427052015-10-15 16:29:00 +09001872 /** {@hide} */
1873 public static final void enforceChangePermission(Context context) {
1874 int uid = Binder.getCallingUid();
1875 Settings.checkAndNoteChangeNetworkStateOperation(context, uid, Settings
1876 .getPackageNameForUid(context, uid), true /* throwException */);
1877 }
1878
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09001879 /** {@hide} */
1880 public static final void enforceTetherChangePermission(Context context, String callingPkg) {
Hugo Benichie7678512017-05-09 15:19:01 +09001881 Preconditions.checkNotNull(context, "Context cannot be null");
1882 Preconditions.checkNotNull(callingPkg, "callingPkg cannot be null");
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09001883
Robert Greenwaltedb47662014-09-16 17:54:19 -07001884 if (context.getResources().getStringArray(
1885 com.android.internal.R.array.config_mobile_hotspot_provision_app).length == 2) {
1886 // Have a provisioning app - must only let system apps (which check this app)
1887 // turn on tethering
1888 context.enforceCallingOrSelfPermission(
Jeremy Kleind42209d2015-12-28 15:11:58 -08001889 android.Manifest.permission.TETHER_PRIVILEGED, "ConnectivityService");
Robert Greenwaltedb47662014-09-16 17:54:19 -07001890 } else {
Billy Laua7238a32015-08-01 12:45:02 +01001891 int uid = Binder.getCallingUid();
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09001892 // If callingPkg's uid is not same as Binder.getCallingUid(),
1893 // AppOpsService throws SecurityException.
1894 Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPkg,
1895 true /* throwException */);
Robert Greenwaltedb47662014-09-16 17:54:19 -07001896 }
1897 }
1898
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001899 /**
Paul Jensene0bef712014-12-10 15:12:18 -05001900 * @deprecated - use getSystemService. This is a kludge to support static access in certain
1901 * situations where a Context pointer is unavailable.
1902 * @hide
1903 */
Paul Jensen72db88e2015-03-10 10:54:12 -04001904 static ConnectivityManager getInstanceOrNull() {
1905 return sInstance;
1906 }
1907
1908 /**
1909 * @deprecated - use getSystemService. This is a kludge to support static access in certain
1910 * situations where a Context pointer is unavailable.
1911 * @hide
1912 */
1913 private static ConnectivityManager getInstance() {
1914 if (getInstanceOrNull() == null) {
Paul Jensene0bef712014-12-10 15:12:18 -05001915 throw new IllegalStateException("No ConnectivityManager yet constructed");
1916 }
Paul Jensen72db88e2015-03-10 10:54:12 -04001917 return getInstanceOrNull();
Paul Jensene0bef712014-12-10 15:12:18 -05001918 }
1919
1920 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001921 * Get the set of tetherable, available interfaces. This list is limited by
1922 * device configuration and current interface existence.
Paul Jensenb2748922015-05-06 11:10:18 -04001923 * <p>This method requires the caller to hold the permission
1924 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001925 *
1926 * @return an array of 0 or more Strings of tetherable interface names.
1927 *
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001928 * {@hide}
1929 */
1930 public String[] getTetherableIfaces() {
1931 try {
1932 return mService.getTetherableIfaces();
1933 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001934 throw e.rethrowFromSystemServer();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001935 }
1936 }
1937
1938 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001939 * Get the set of tethered interfaces.
Paul Jensenb2748922015-05-06 11:10:18 -04001940 * <p>This method requires the caller to hold the permission
1941 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001942 *
1943 * @return an array of 0 or more String of currently tethered interface names.
1944 *
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001945 * {@hide}
1946 */
1947 public String[] getTetheredIfaces() {
1948 try {
1949 return mService.getTetheredIfaces();
1950 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001951 throw e.rethrowFromSystemServer();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001952 }
1953 }
1954
1955 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001956 * Get the set of interface names which attempted to tether but
1957 * failed. Re-attempting to tether may cause them to reset to the Tethered
1958 * state. Alternatively, causing the interface to be destroyed and recreated
1959 * may cause them to reset to the available state.
1960 * {@link ConnectivityManager#getLastTetherError} can be used to get more
1961 * information on the cause of the errors.
Paul Jensenb2748922015-05-06 11:10:18 -04001962 * <p>This method requires the caller to hold the permission
1963 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001964 *
1965 * @return an array of 0 or more String indicating the interface names
1966 * which failed to tether.
1967 *
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001968 * {@hide}
1969 */
Robert Greenwalt5a735062010-03-02 17:25:02 -08001970 public String[] getTetheringErroredIfaces() {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001971 try {
Robert Greenwalt5a735062010-03-02 17:25:02 -08001972 return mService.getTetheringErroredIfaces();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001973 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001974 throw e.rethrowFromSystemServer();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001975 }
1976 }
1977
1978 /**
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07001979 * Get the set of tethered dhcp ranges.
1980 *
1981 * @return an array of 0 or more {@code String} of tethered dhcp ranges.
1982 * {@hide}
1983 */
1984 public String[] getTetheredDhcpRanges() {
1985 try {
1986 return mService.getTetheredDhcpRanges();
1987 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001988 throw e.rethrowFromSystemServer();
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07001989 }
1990 }
1991
1992 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001993 * Attempt to tether the named interface. This will setup a dhcp server
1994 * on the interface, forward and NAT IP packets and forward DNS requests
1995 * to the best active upstream network interface. Note that if no upstream
1996 * IP network interface is available, dhcp will still run and traffic will be
1997 * allowed between the tethered devices and this device, though upstream net
1998 * access will of course fail until an upstream network interface becomes
1999 * active.
Lorenzo Colittid5427052015-10-15 16:29:00 +09002000 *
2001 * <p>This method requires the caller to hold either the
2002 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2003 * or the ability to modify system settings as determined by
2004 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002005 *
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002006 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2007 * and WifiStateMachine which need direct access. All other clients should use
2008 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2009 * logic.</p>
2010 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002011 * @param iface the interface name to tether.
2012 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2013 *
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002014 * {@hide}
2015 */
Robert Greenwalt5a735062010-03-02 17:25:02 -08002016 public int tether(String iface) {
2017 try {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002018 String pkgName = mContext.getOpPackageName();
2019 Log.i(TAG, "tether caller:" + pkgName);
2020 return mService.tether(iface, pkgName);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002021 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002022 throw e.rethrowFromSystemServer();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002023 }
2024 }
2025
2026 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002027 * Stop tethering the named interface.
Lorenzo Colittid5427052015-10-15 16:29:00 +09002028 *
2029 * <p>This method requires the caller to hold either the
2030 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2031 * or the ability to modify system settings as determined by
2032 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002033 *
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002034 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2035 * and WifiStateMachine which need direct access. All other clients should use
2036 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2037 * logic.</p>
2038 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002039 * @param iface the interface name to untether.
2040 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2041 *
Robert Greenwalt5a735062010-03-02 17:25:02 -08002042 * {@hide}
2043 */
2044 public int untether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002045 try {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002046 String pkgName = mContext.getOpPackageName();
2047 Log.i(TAG, "untether caller:" + pkgName);
2048 return mService.untether(iface, pkgName);
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002049 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002050 throw e.rethrowFromSystemServer();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002051 }
2052 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002053
2054 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002055 * Check if the device allows for tethering. It may be disabled via
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002056 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002057 * due to device configuration.
Paul Jensenb2748922015-05-06 11:10:18 -04002058 * <p>This method requires the caller to hold the permission
2059 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002060 *
2061 * @return a boolean - {@code true} indicating Tethering is supported.
2062 *
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002063 * {@hide}
2064 */
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002065 @SystemApi
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002066 public boolean isTetheringSupported() {
2067 try {
2068 return mService.isTetheringSupported();
2069 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002070 throw e.rethrowFromSystemServer();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002071 }
2072 }
2073
2074 /**
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002075 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
2076 * @hide
2077 */
2078 @SystemApi
2079 public static abstract class OnStartTetheringCallback {
2080 /**
2081 * Called when tethering has been successfully started.
2082 */
2083 public void onTetheringStarted() {};
2084
2085 /**
2086 * Called when starting tethering failed.
2087 */
2088 public void onTetheringFailed() {};
2089 }
2090
2091 /**
2092 * Convenient overload for
2093 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
2094 * handler to run on the current thread's {@link Looper}.
2095 * @hide
2096 */
2097 @SystemApi
2098 public void startTethering(int type, boolean showProvisioningUi,
2099 final OnStartTetheringCallback callback) {
2100 startTethering(type, showProvisioningUi, callback, null);
2101 }
2102
2103 /**
2104 * Runs tether provisioning for the given type if needed and then starts tethering if
2105 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
2106 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
2107 * schedules tether provisioning re-checks if appropriate.
2108 *
2109 * @param type The type of tethering to start. Must be one of
2110 * {@link ConnectivityManager.TETHERING_WIFI},
2111 * {@link ConnectivityManager.TETHERING_USB}, or
2112 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2113 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
2114 * is one. This should be true the first time this function is called and also any time
2115 * the user can see this UI. It gives users information from their carrier about the
2116 * check failing and how they can sign up for tethering if possible.
2117 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
2118 * of the result of trying to tether.
2119 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
2120 * @hide
2121 */
2122 @SystemApi
2123 public void startTethering(int type, boolean showProvisioningUi,
2124 final OnStartTetheringCallback callback, Handler handler) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09002125 Preconditions.checkNotNull(callback, "OnStartTetheringCallback cannot be null.");
Jeremy Kleina17dabe2016-03-12 16:29:54 -08002126
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002127 ResultReceiver wrappedCallback = new ResultReceiver(handler) {
2128 @Override
2129 protected void onReceiveResult(int resultCode, Bundle resultData) {
2130 if (resultCode == TETHER_ERROR_NO_ERROR) {
2131 callback.onTetheringStarted();
2132 } else {
2133 callback.onTetheringFailed();
2134 }
2135 }
2136 };
Jeremy Kleina17dabe2016-03-12 16:29:54 -08002137
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002138 try {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002139 String pkgName = mContext.getOpPackageName();
2140 Log.i(TAG, "startTethering caller:" + pkgName);
2141 mService.startTethering(type, wrappedCallback, showProvisioningUi, pkgName);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002142 } catch (RemoteException e) {
2143 Log.e(TAG, "Exception trying to start tethering.", e);
2144 wrappedCallback.send(TETHER_ERROR_SERVICE_UNAVAIL, null);
2145 }
2146 }
2147
2148 /**
2149 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
2150 * applicable.
2151 *
2152 * @param type The type of tethering to stop. Must be one of
2153 * {@link ConnectivityManager.TETHERING_WIFI},
2154 * {@link ConnectivityManager.TETHERING_USB}, or
2155 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2156 * @hide
2157 */
2158 @SystemApi
2159 public void stopTethering(int type) {
2160 try {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002161 String pkgName = mContext.getOpPackageName();
2162 Log.i(TAG, "stopTethering caller:" + pkgName);
2163 mService.stopTethering(type, pkgName);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002164 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002165 throw e.rethrowFromSystemServer();
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002166 }
2167 }
2168
2169 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002170 * Get the list of regular expressions that define any tetherable
2171 * USB network interfaces. If USB tethering is not supported by the
2172 * device, this list should be empty.
Paul Jensenb2748922015-05-06 11:10:18 -04002173 * <p>This method requires the caller to hold the permission
2174 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002175 *
2176 * @return an array of 0 or more regular expression Strings defining
2177 * what interfaces are considered tetherable usb interfaces.
2178 *
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002179 * {@hide}
2180 */
2181 public String[] getTetherableUsbRegexs() {
2182 try {
2183 return mService.getTetherableUsbRegexs();
2184 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002185 throw e.rethrowFromSystemServer();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002186 }
2187 }
2188
2189 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002190 * Get the list of regular expressions that define any tetherable
2191 * Wifi network interfaces. If Wifi tethering is not supported by the
2192 * device, this list should be empty.
Paul Jensenb2748922015-05-06 11:10:18 -04002193 * <p>This method requires the caller to hold the permission
2194 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002195 *
2196 * @return an array of 0 or more regular expression Strings defining
2197 * what interfaces are considered tetherable wifi interfaces.
2198 *
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002199 * {@hide}
2200 */
2201 public String[] getTetherableWifiRegexs() {
2202 try {
2203 return mService.getTetherableWifiRegexs();
2204 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002205 throw e.rethrowFromSystemServer();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002206 }
2207 }
Robert Greenwalt5a735062010-03-02 17:25:02 -08002208
Danica Chang6fdd0c62010-08-11 14:54:43 -07002209 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002210 * Get the list of regular expressions that define any tetherable
2211 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
2212 * device, this list should be empty.
Paul Jensenb2748922015-05-06 11:10:18 -04002213 * <p>This method requires the caller to hold the permission
2214 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002215 *
2216 * @return an array of 0 or more regular expression Strings defining
2217 * what interfaces are considered tetherable bluetooth interfaces.
2218 *
Danica Chang6fdd0c62010-08-11 14:54:43 -07002219 * {@hide}
2220 */
2221 public String[] getTetherableBluetoothRegexs() {
2222 try {
2223 return mService.getTetherableBluetoothRegexs();
2224 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002225 throw e.rethrowFromSystemServer();
Danica Chang6fdd0c62010-08-11 14:54:43 -07002226 }
2227 }
2228
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002229 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002230 * Attempt to both alter the mode of USB and Tethering of USB. A
2231 * utility method to deal with some of the complexity of USB - will
2232 * attempt to switch to Rndis and subsequently tether the resulting
2233 * interface on {@code true} or turn off tethering and switch off
2234 * Rndis on {@code false}.
Lorenzo Colittid5427052015-10-15 16:29:00 +09002235 *
2236 * <p>This method requires the caller to hold either the
2237 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2238 * or the ability to modify system settings as determined by
2239 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002240 *
2241 * @param enable a boolean - {@code true} to enable tethering
2242 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2243 *
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002244 * {@hide}
2245 */
2246 public int setUsbTethering(boolean enable) {
2247 try {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002248 String pkgName = mContext.getOpPackageName();
2249 Log.i(TAG, "setUsbTethering caller:" + pkgName);
2250 return mService.setUsbTethering(enable, pkgName);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002251 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002252 throw e.rethrowFromSystemServer();
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002253 }
2254 }
2255
Robert Greenwalt5a735062010-03-02 17:25:02 -08002256 /** {@hide} */
2257 public static final int TETHER_ERROR_NO_ERROR = 0;
2258 /** {@hide} */
2259 public static final int TETHER_ERROR_UNKNOWN_IFACE = 1;
2260 /** {@hide} */
2261 public static final int TETHER_ERROR_SERVICE_UNAVAIL = 2;
2262 /** {@hide} */
2263 public static final int TETHER_ERROR_UNSUPPORTED = 3;
2264 /** {@hide} */
2265 public static final int TETHER_ERROR_UNAVAIL_IFACE = 4;
2266 /** {@hide} */
2267 public static final int TETHER_ERROR_MASTER_ERROR = 5;
2268 /** {@hide} */
2269 public static final int TETHER_ERROR_TETHER_IFACE_ERROR = 6;
2270 /** {@hide} */
2271 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR = 7;
2272 /** {@hide} */
2273 public static final int TETHER_ERROR_ENABLE_NAT_ERROR = 8;
2274 /** {@hide} */
2275 public static final int TETHER_ERROR_DISABLE_NAT_ERROR = 9;
2276 /** {@hide} */
2277 public static final int TETHER_ERROR_IFACE_CFG_ERROR = 10;
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002278 /** {@hide} */
2279 public static final int TETHER_ERROR_PROVISION_FAILED = 11;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002280
2281 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002282 * Get a more detailed error code after a Tethering or Untethering
2283 * request asynchronously failed.
Paul Jensenb2748922015-05-06 11:10:18 -04002284 * <p>This method requires the caller to hold the permission
2285 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002286 *
2287 * @param iface The name of the interface of interest
Robert Greenwalt5a735062010-03-02 17:25:02 -08002288 * @return error The error code of the last error tethering or untethering the named
2289 * interface
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002290 *
Robert Greenwalt5a735062010-03-02 17:25:02 -08002291 * {@hide}
2292 */
2293 public int getLastTetherError(String iface) {
2294 try {
2295 return mService.getLastTetherError(iface);
2296 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002297 throw e.rethrowFromSystemServer();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002298 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002299 }
2300
2301 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002302 * Report network connectivity status. This is currently used only
2303 * to alter status bar UI.
Paul Jensenb2748922015-05-06 11:10:18 -04002304 * <p>This method requires the caller to hold the permission
2305 * {@link android.Manifest.permission#STATUS_BAR}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002306 *
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002307 * @param networkType The type of network you want to report on
2308 * @param percentage The quality of the connection 0 is bad, 100 is good
2309 * {@hide}
2310 */
2311 public void reportInetCondition(int networkType, int percentage) {
2312 try {
2313 mService.reportInetCondition(networkType, percentage);
2314 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002315 throw e.rethrowFromSystemServer();
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002316 }
2317 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002318
2319 /**
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002320 * Report a problem network to the framework. This provides a hint to the system
Ye Wenb87875e2014-07-21 14:19:01 -07002321 * that there might be connectivity problems on this network and may cause
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002322 * the framework to re-evaluate network connectivity and/or switch to another
2323 * network.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002324 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002325 * @param network The {@link Network} the application was attempting to use
2326 * or {@code null} to indicate the current default network.
Paul Jensenbfd17b72015-04-07 12:43:13 -04002327 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
2328 * working and non-working connectivity.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002329 */
2330 public void reportBadNetwork(Network network) {
2331 try {
Paul Jensenbfd17b72015-04-07 12:43:13 -04002332 // One of these will be ignored because it matches system's current state.
2333 // The other will trigger the necessary reevaluation.
2334 mService.reportNetworkConnectivity(network, true);
2335 mService.reportNetworkConnectivity(network, false);
2336 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002337 throw e.rethrowFromSystemServer();
Paul Jensenbfd17b72015-04-07 12:43:13 -04002338 }
2339 }
2340
2341 /**
2342 * Report to the framework whether a network has working connectivity.
2343 * This provides a hint to the system that a particular network is providing
2344 * working connectivity or not. In response the framework may re-evaluate
2345 * the network's connectivity and might take further action thereafter.
2346 *
2347 * @param network The {@link Network} the application was attempting to use
2348 * or {@code null} to indicate the current default network.
2349 * @param hasConnectivity {@code true} if the application was able to successfully access the
2350 * Internet using {@code network} or {@code false} if not.
2351 */
2352 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
2353 try {
2354 mService.reportNetworkConnectivity(network, hasConnectivity);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002355 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002356 throw e.rethrowFromSystemServer();
Robert Greenwalt9258c642014-03-26 16:47:06 -07002357 }
2358 }
2359
2360 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002361 * Set a network-independent global http proxy. This is not normally what you want
2362 * for typical HTTP proxies - they are general network dependent. However if you're
2363 * doing something unusual like general internal filtering this may be useful. On
2364 * a private network where the proxy is not accessible, you may break HTTP using this.
Paul Jensen0d719ca2015-02-13 14:18:39 -05002365 * <p>This method requires the caller to hold the permission
Jason Monkfaf3fd52014-05-07 18:41:13 -04002366 * android.Manifest.permission#CONNECTIVITY_INTERNAL.
Paul Jensenb2748922015-05-06 11:10:18 -04002367 *
2368 * @param p A {@link ProxyInfo} object defining the new global
2369 * HTTP proxy. A {@code null} value will clear the global HTTP proxy.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002370 * @hide
Robert Greenwalt434203a2010-10-11 16:00:27 -07002371 */
Jason Monk207900c2014-04-25 15:00:09 -04002372 public void setGlobalProxy(ProxyInfo p) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002373 try {
2374 mService.setGlobalProxy(p);
2375 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002376 throw e.rethrowFromSystemServer();
Robert Greenwalt434203a2010-10-11 16:00:27 -07002377 }
2378 }
2379
2380 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002381 * Retrieve any network-independent global HTTP proxy.
2382 *
Jason Monk207900c2014-04-25 15:00:09 -04002383 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002384 * if no global HTTP proxy is set.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002385 * @hide
Robert Greenwalt434203a2010-10-11 16:00:27 -07002386 */
Jason Monk207900c2014-04-25 15:00:09 -04002387 public ProxyInfo getGlobalProxy() {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002388 try {
2389 return mService.getGlobalProxy();
2390 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002391 throw e.rethrowFromSystemServer();
Robert Greenwalt434203a2010-10-11 16:00:27 -07002392 }
2393 }
2394
2395 /**
Paul Jensencee9b512015-05-06 07:32:40 -04002396 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
2397 * network-specific HTTP proxy. If {@code network} is null, the
2398 * network-specific proxy returned is the proxy of the default active
2399 * network.
2400 *
2401 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
2402 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
2403 * or when {@code network} is {@code null},
2404 * the {@code ProxyInfo} for the default active network. Returns
2405 * {@code null} when no proxy applies or the caller doesn't have
2406 * permission to use {@code network}.
2407 * @hide
2408 */
2409 public ProxyInfo getProxyForNetwork(Network network) {
2410 try {
2411 return mService.getProxyForNetwork(network);
2412 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002413 throw e.rethrowFromSystemServer();
Paul Jensencee9b512015-05-06 07:32:40 -04002414 }
2415 }
2416
2417 /**
Paul Jensene0bef712014-12-10 15:12:18 -05002418 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
2419 * otherwise if this process is bound to a {@link Network} using
Paul Jensen72db88e2015-03-10 10:54:12 -04002420 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
Paul Jensene0bef712014-12-10 15:12:18 -05002421 * the default network's proxy is returned.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002422 *
Jason Monk207900c2014-04-25 15:00:09 -04002423 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002424 * HTTP proxy is active.
Robert Greenwalt434203a2010-10-11 16:00:27 -07002425 */
Paul Jensene0bef712014-12-10 15:12:18 -05002426 public ProxyInfo getDefaultProxy() {
Paul Jensencee9b512015-05-06 07:32:40 -04002427 return getProxyForNetwork(getBoundNetworkForProcess());
Robert Greenwalt434203a2010-10-11 16:00:27 -07002428 }
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002429
2430 /**
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07002431 * Returns true if the hardware supports the given network type
2432 * else it returns false. This doesn't indicate we have coverage
2433 * or are authorized onto a network, just whether or not the
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002434 * hardware supports it. For example a GSM phone without a SIM
2435 * should still return {@code true} for mobile data, but a wifi only
2436 * tablet would return {@code false}.
Paul Jensenb2748922015-05-06 11:10:18 -04002437 * <p>This method requires the caller to hold the permission
2438 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002439 *
2440 * @param networkType The network type we'd like to check
2441 * @return {@code true} if supported, else {@code false}
2442 *
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07002443 * @hide
2444 */
2445 public boolean isNetworkSupported(int networkType) {
2446 try {
2447 return mService.isNetworkSupported(networkType);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002448 } catch (RemoteException e) {
2449 throw e.rethrowFromSystemServer();
2450 }
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07002451 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002452
2453 /**
2454 * Returns if the currently active data network is metered. A network is
2455 * classified as metered when the user is sensitive to heavy data usage on
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002456 * that connection due to monetary costs, data limitations or
2457 * battery/performance issues. You should check this before doing large
2458 * data transfers, and warn the user or delay the operation until another
2459 * network is available.
Paul Jensenb2748922015-05-06 11:10:18 -04002460 * <p>This method requires the caller to hold the permission
2461 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002462 *
2463 * @return {@code true} if large transfers should be avoided, otherwise
2464 * {@code false}.
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002465 */
2466 public boolean isActiveNetworkMetered() {
2467 try {
2468 return mService.isActiveNetworkMetered();
2469 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002470 throw e.rethrowFromSystemServer();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002471 }
2472 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002473
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002474 /**
2475 * If the LockdownVpn mechanism is enabled, updates the vpn
2476 * with a reload of its profile.
2477 *
2478 * @return a boolean with {@code} indicating success
2479 *
2480 * <p>This method can only be called by the system UID
2481 * {@hide}
2482 */
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002483 public boolean updateLockdownVpn() {
2484 try {
2485 return mService.updateLockdownVpn();
2486 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002487 throw e.rethrowFromSystemServer();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002488 }
2489 }
Irfan Sheriffda6da092012-08-16 12:49:23 -07002490
2491 /**
Wink Saville948282b2013-08-29 08:55:16 -07002492 * Check mobile provisioning.
Wink Savilleab9321d2013-06-29 21:10:57 -07002493 *
Wink Savilleab9321d2013-06-29 21:10:57 -07002494 * @param suggestedTimeOutMs, timeout in milliseconds
Wink Savilleab9321d2013-06-29 21:10:57 -07002495 *
2496 * @return time out that will be used, maybe less that suggestedTimeOutMs
2497 * -1 if an error.
2498 *
2499 * {@hide}
2500 */
Wink Saville948282b2013-08-29 08:55:16 -07002501 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Wink Savilleab9321d2013-06-29 21:10:57 -07002502 int timeOutMs = -1;
2503 try {
Wink Saville948282b2013-08-29 08:55:16 -07002504 timeOutMs = mService.checkMobileProvisioning(suggestedTimeOutMs);
Wink Savilleab9321d2013-06-29 21:10:57 -07002505 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002506 throw e.rethrowFromSystemServer();
Wink Savilleab9321d2013-06-29 21:10:57 -07002507 }
2508 return timeOutMs;
2509 }
Robert Greenwalte182bfe2013-07-16 12:06:09 -07002510
2511 /**
Wink Saville42d4f082013-07-20 20:31:59 -07002512 * Get the mobile provisioning url.
Robert Greenwalte182bfe2013-07-16 12:06:09 -07002513 * {@hide}
2514 */
2515 public String getMobileProvisioningUrl() {
2516 try {
2517 return mService.getMobileProvisioningUrl();
2518 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002519 throw e.rethrowFromSystemServer();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07002520 }
Robert Greenwalte182bfe2013-07-16 12:06:09 -07002521 }
Wink Saville42d4f082013-07-20 20:31:59 -07002522
2523 /**
Wink Saville948282b2013-08-29 08:55:16 -07002524 * Set sign in error notification to visible or in visible
2525 *
2526 * @param visible
2527 * @param networkType
2528 *
2529 * {@hide}
Paul Jensen3541e9f2015-03-18 12:23:02 -04002530 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
Wink Saville948282b2013-08-29 08:55:16 -07002531 */
2532 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04002533 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07002534 try {
Paul Jensen89e0f092014-09-15 15:59:36 -04002535 mService.setProvisioningNotificationVisible(visible, networkType, action);
Wink Saville948282b2013-08-29 08:55:16 -07002536 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002537 throw e.rethrowFromSystemServer();
Wink Saville948282b2013-08-29 08:55:16 -07002538 }
2539 }
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07002540
2541 /**
2542 * Set the value for enabling/disabling airplane mode
Paul Jensenb2748922015-05-06 11:10:18 -04002543 * <p>This method requires the caller to hold the permission
2544 * {@link android.Manifest.permission#CONNECTIVITY_INTERNAL}.
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07002545 *
2546 * @param enable whether to enable airplane mode or not
2547 *
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07002548 * @hide
2549 */
2550 public void setAirplaneMode(boolean enable) {
2551 try {
2552 mService.setAirplaneMode(enable);
2553 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002554 throw e.rethrowFromSystemServer();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07002555 }
2556 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002557
2558 /** {@hide} */
Robert Greenwalta67be032014-05-16 15:49:14 -07002559 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07002560 try {
Robert Greenwalta67be032014-05-16 15:49:14 -07002561 mService.registerNetworkFactory(messenger, name);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002562 } catch (RemoteException e) {
2563 throw e.rethrowFromSystemServer();
2564 }
Robert Greenwalta67be032014-05-16 15:49:14 -07002565 }
2566
2567 /** {@hide} */
2568 public void unregisterNetworkFactory(Messenger messenger) {
2569 try {
2570 mService.unregisterNetworkFactory(messenger);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002571 } catch (RemoteException e) {
2572 throw e.rethrowFromSystemServer();
2573 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002574 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002575
Paul Jensen31a94f42015-02-13 14:18:39 -05002576 /**
2577 * @hide
2578 * Register a NetworkAgent with ConnectivityService.
2579 * @return NetID corresponding to NetworkAgent.
2580 */
2581 public int registerNetworkAgent(Messenger messenger, NetworkInfo ni, LinkProperties lp,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07002582 NetworkCapabilities nc, int score, NetworkMisc misc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002583 try {
Paul Jensen31a94f42015-02-13 14:18:39 -05002584 return mService.registerNetworkAgent(messenger, ni, lp, nc, score, misc);
2585 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002586 throw e.rethrowFromSystemServer();
Paul Jensen31a94f42015-02-13 14:18:39 -05002587 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002588 }
2589
Robert Greenwalt9258c642014-03-26 16:47:06 -07002590 /**
Hugo Benichidafed3d2017-03-06 09:17:06 +09002591 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
2592 * changes. Should be extended by applications wanting notifications.
2593 *
2594 * A {@code NetworkCallback} is registered by calling
2595 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2596 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
2597 * or {@link #registerDefaultNetworkCallback(NetworkCallback). A {@code NetworkCallback} is
2598 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
2599 * A {@code NetworkCallback} should be registered at most once at any time.
2600 * A {@code NetworkCallback} that has been unregistered can be registered again.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002601 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07002602 public static class NetworkCallback {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002603 /**
Lorenzo Colitti07086932015-04-24 12:23:24 +09002604 * Called when the framework connects to a new network to evaluate whether it satisfies this
2605 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
2606 * callback. There is no guarantee that this new network will satisfy any requests, or that
2607 * the network will stay connected for longer than the time necessary to evaluate it.
2608 * <p>
2609 * Most applications <b>should not</b> act on this callback, and should instead use
2610 * {@link #onAvailable}. This callback is intended for use by applications that can assist
2611 * the framework in properly evaluating the network &mdash; for example, an application that
2612 * can automatically log in to a captive portal without user intervention.
2613 *
2614 * @param network The {@link Network} of the network that is being evaluated.
Lorenzo Colitti66276122015-06-11 14:27:17 +09002615 *
2616 * @hide
Robert Greenwalt7b816022014-04-18 15:25:25 -07002617 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07002618 public void onPreCheck(Network network) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07002619
2620 /**
Lorenzo Colitti07086932015-04-24 12:23:24 +09002621 * Called when the framework connects and has declared a new network ready for use.
Robert Greenwalt6078b502014-06-11 16:05:07 -07002622 * This callback may be called more than once if the {@link Network} that is
2623 * satisfying the request changes.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002624 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002625 * @param network The {@link Network} of the satisfying network.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002626 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07002627 public void onAvailable(Network network) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07002628
2629 /**
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002630 * Called when the network is about to be disconnected. Often paired with an
Robert Greenwalt6078b502014-06-11 16:05:07 -07002631 * {@link NetworkCallback#onAvailable} call with the new replacement network
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002632 * for graceful handover. This may not be called if we have a hard loss
2633 * (loss without warning). This may be followed by either a
Robert Greenwalt6078b502014-06-11 16:05:07 -07002634 * {@link NetworkCallback#onLost} call or a
2635 * {@link NetworkCallback#onAvailable} call for this network depending
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002636 * on whether we lose or regain it.
2637 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07002638 * @param network The {@link Network} that is about to be disconnected.
2639 * @param maxMsToLive The time in ms the framework will attempt to keep the
2640 * network connected. Note that the network may suffer a
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002641 * hard loss at any time.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002642 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07002643 public void onLosing(Network network, int maxMsToLive) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07002644
2645 /**
2646 * Called when the framework has a hard loss of the network or when the
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002647 * graceful failure ends.
2648 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002649 * @param network The {@link Network} lost.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002650 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07002651 public void onLost(Network network) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07002652
2653 /**
Etan Cohenaebf17e2017-03-01 12:47:28 -08002654 * Called if no network is found in the timeout time specified in
Hugo Benichi0eec03f2017-05-15 15:15:33 +09002655 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call. This callback is not
Etan Cohenaebf17e2017-03-01 12:47:28 -08002656 * called for the version of {@link #requestNetwork(NetworkRequest, NetworkCallback)}
2657 * without timeout. When this callback is invoked the associated
2658 * {@link NetworkRequest} will have already been removed and released, as if
2659 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002660 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07002661 public void onUnavailable() {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07002662
2663 /**
2664 * Called when the network the framework connected to for this request
2665 * changes capabilities but still satisfies the stated need.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002666 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002667 * @param network The {@link Network} whose capabilities have changed.
Lorenzo Colittie285b432015-04-23 15:32:42 +09002668 * @param networkCapabilities The new {@link android.net.NetworkCapabilities} for this network.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002669 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07002670 public void onCapabilitiesChanged(Network network,
Robert Greenwalt7b816022014-04-18 15:25:25 -07002671 NetworkCapabilities networkCapabilities) {}
2672
2673 /**
2674 * Called when the network the framework connected to for this request
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002675 * changes {@link LinkProperties}.
2676 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002677 * @param network The {@link Network} whose link properties have changed.
2678 * @param linkProperties The new {@link LinkProperties} for this network.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002679 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07002680 public void onLinkPropertiesChanged(Network network, LinkProperties linkProperties) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07002681
Robert Greenwalt8d482522015-06-24 13:23:42 -07002682 /**
2683 * Called when the network the framework connected to for this request
2684 * goes into {@link NetworkInfo.DetailedState.SUSPENDED}.
2685 * This generally means that while the TCP connections are still live,
2686 * temporarily network data fails to transfer. Specifically this is used
2687 * on cellular networks to mask temporary outages when driving through
2688 * a tunnel, etc.
2689 * @hide
2690 */
2691 public void onNetworkSuspended(Network network) {}
2692
2693 /**
2694 * Called when the network the framework connected to for this request
2695 * returns from a {@link NetworkInfo.DetailedState.SUSPENDED} state.
2696 * This should always be preceeded by a matching {@code onNetworkSuspended}
2697 * call.
2698 * @hide
2699 */
2700 public void onNetworkResumed(Network network) {}
2701
Robert Greenwalt6078b502014-06-11 16:05:07 -07002702 private NetworkRequest networkRequest;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002703 }
2704
Hugo Benichicb883232017-05-11 13:16:17 +09002705 /**
2706 * Constant error codes used by ConnectivityService to communicate about failures and errors
2707 * across a Binder boundary.
2708 * @hide
2709 */
2710 public interface Errors {
2711 static int TOO_MANY_REQUESTS = 1;
2712 }
2713
2714 /** @hide */
2715 public static class TooManyRequestsException extends RuntimeException {}
2716
2717 private static RuntimeException convertServiceException(ServiceSpecificException e) {
2718 switch (e.errorCode) {
2719 case Errors.TOO_MANY_REQUESTS:
2720 return new TooManyRequestsException();
2721 default:
2722 Log.w(TAG, "Unknown service error code " + e.errorCode);
2723 return new RuntimeException(e);
2724 }
2725 }
2726
Robert Greenwalt9258c642014-03-26 16:47:06 -07002727 private static final int BASE = Protocol.BASE_CONNECTIVITY_MANAGER;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002728 /** @hide */
Robert Greenwalt8d482522015-06-24 13:23:42 -07002729 public static final int CALLBACK_PRECHECK = BASE + 1;
2730 /** @hide */
2731 public static final int CALLBACK_AVAILABLE = BASE + 2;
2732 /** @hide arg1 = TTL */
2733 public static final int CALLBACK_LOSING = BASE + 3;
2734 /** @hide */
2735 public static final int CALLBACK_LOST = BASE + 4;
2736 /** @hide */
2737 public static final int CALLBACK_UNAVAIL = BASE + 5;
2738 /** @hide */
2739 public static final int CALLBACK_CAP_CHANGED = BASE + 6;
2740 /** @hide */
2741 public static final int CALLBACK_IP_CHANGED = BASE + 7;
Robert Greenwalt562cc542014-05-15 18:07:26 -07002742 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Hugo Benichidba33db2017-03-23 22:40:44 +09002743 private static final int EXPIRE_LEGACY_REQUEST = BASE + 8;
Robert Greenwalt8d482522015-06-24 13:23:42 -07002744 /** @hide */
Hugo Benichidba33db2017-03-23 22:40:44 +09002745 public static final int CALLBACK_SUSPENDED = BASE + 9;
Robert Greenwalt8d482522015-06-24 13:23:42 -07002746 /** @hide */
Hugo Benichidba33db2017-03-23 22:40:44 +09002747 public static final int CALLBACK_RESUMED = BASE + 10;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002748
Erik Kline95be6232015-11-25 12:49:38 +09002749 /** @hide */
2750 public static String getCallbackName(int whichCallback) {
2751 switch (whichCallback) {
2752 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
2753 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
2754 case CALLBACK_LOSING: return "CALLBACK_LOSING";
2755 case CALLBACK_LOST: return "CALLBACK_LOST";
2756 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
2757 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
2758 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
Erik Kline95be6232015-11-25 12:49:38 +09002759 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
2760 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
2761 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
2762 default:
2763 return Integer.toString(whichCallback);
2764 }
2765 }
2766
Robert Greenwalt562cc542014-05-15 18:07:26 -07002767 private class CallbackHandler extends Handler {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002768 private static final String TAG = "ConnectivityManager.CallbackHandler";
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07002769 private static final boolean DBG = false;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002770
Hugo Benichi9c58a112016-07-06 22:53:17 +09002771 CallbackHandler(Looper looper) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002772 super(looper);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002773 }
2774
Hugo Benichi2583ef02017-02-02 17:02:36 +09002775 CallbackHandler(Handler handler) {
Hugo Benichie7678512017-05-09 15:19:01 +09002776 this(Preconditions.checkNotNull(handler, "Handler cannot be null.").getLooper());
Hugo Benichi2583ef02017-02-02 17:02:36 +09002777 }
2778
Robert Greenwalt9258c642014-03-26 16:47:06 -07002779 @Override
2780 public void handleMessage(Message message) {
Hugo Benichi2c684522017-05-09 14:36:02 +09002781 if (message.what == EXPIRE_LEGACY_REQUEST) {
2782 expireRequest((NetworkCapabilities) message.obj, message.arg1);
2783 return;
2784 }
2785
2786 final NetworkRequest request = getObject(message, NetworkRequest.class);
2787 final Network network = getObject(message, Network.class);
2788 final NetworkCallback callback;
2789 synchronized (sCallbacks) {
2790 callback = sCallbacks.get(request);
2791 }
Lorenzo Colittifcfa7d92016-03-01 22:56:37 +09002792 if (DBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09002793 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
Lorenzo Colittifcfa7d92016-03-01 22:56:37 +09002794 }
Hugo Benichi2c684522017-05-09 14:36:02 +09002795 if (callback == null) {
2796 Log.w(TAG, "callback not found for " + getCallbackName(message.what) + " message");
2797 return;
2798 }
2799
Robert Greenwalt9258c642014-03-26 16:47:06 -07002800 switch (message.what) {
2801 case CALLBACK_PRECHECK: {
Hugo Benichi2c684522017-05-09 14:36:02 +09002802 callback.onPreCheck(network);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002803 break;
2804 }
2805 case CALLBACK_AVAILABLE: {
Hugo Benichi2c684522017-05-09 14:36:02 +09002806 callback.onAvailable(network);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002807 break;
2808 }
2809 case CALLBACK_LOSING: {
Hugo Benichi2c684522017-05-09 14:36:02 +09002810 callback.onLosing(network, message.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002811 break;
2812 }
2813 case CALLBACK_LOST: {
Hugo Benichi2c684522017-05-09 14:36:02 +09002814 callback.onLost(network);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002815 break;
2816 }
2817 case CALLBACK_UNAVAIL: {
Hugo Benichi2c684522017-05-09 14:36:02 +09002818 callback.onUnavailable();
Robert Greenwalt9258c642014-03-26 16:47:06 -07002819 break;
2820 }
2821 case CALLBACK_CAP_CHANGED: {
Hugo Benichi2c684522017-05-09 14:36:02 +09002822 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
2823 callback.onCapabilitiesChanged(network, cap);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002824 break;
2825 }
2826 case CALLBACK_IP_CHANGED: {
Hugo Benichi2c684522017-05-09 14:36:02 +09002827 LinkProperties lp = getObject(message, LinkProperties.class);
2828 callback.onLinkPropertiesChanged(network, lp);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002829 break;
2830 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07002831 case CALLBACK_SUSPENDED: {
Hugo Benichi2c684522017-05-09 14:36:02 +09002832 callback.onNetworkSuspended(network);
Robert Greenwalt8d482522015-06-24 13:23:42 -07002833 break;
2834 }
2835 case CALLBACK_RESUMED: {
Hugo Benichi2c684522017-05-09 14:36:02 +09002836 callback.onNetworkResumed(network);
Robert Greenwalt562cc542014-05-15 18:07:26 -07002837 break;
2838 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002839 }
2840 }
2841
Hugo Benichi9c58a112016-07-06 22:53:17 +09002842 private <T> T getObject(Message msg, Class<T> c) {
2843 return (T) msg.getData().getParcelable(c.getSimpleName());
Robert Greenwalt9258c642014-03-26 16:47:06 -07002844 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002845 }
2846
Hugo Benichi2583ef02017-02-02 17:02:36 +09002847 private CallbackHandler getDefaultHandler() {
Hugo Benichi1e19aef2016-07-07 10:15:56 +09002848 synchronized (sCallbacks) {
2849 if (sCallbackHandler == null) {
2850 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
Robert Greenwalt9258c642014-03-26 16:47:06 -07002851 }
Hugo Benichi1e19aef2016-07-07 10:15:56 +09002852 return sCallbackHandler;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002853 }
2854 }
2855
Hugo Benichi6f260f32017-02-03 14:18:44 +09002856 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
2857 private static CallbackHandler sCallbackHandler;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002858
Hugo Benichi6f260f32017-02-03 14:18:44 +09002859 private static final int LISTEN = 1;
2860 private static final int REQUEST = 2;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002861
Hugo Benichi6f260f32017-02-03 14:18:44 +09002862 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
2863 int timeoutMs, int action, int legacyType, CallbackHandler handler) {
Hugo Benichie7678512017-05-09 15:19:01 +09002864 checkCallbackNotNull(callback);
Hugo Benichidafed3d2017-03-06 09:17:06 +09002865 Preconditions.checkArgument(action == REQUEST || need != null, "null NetworkCapabilities");
Hugo Benichi9c58a112016-07-06 22:53:17 +09002866 final NetworkRequest request;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002867 try {
Hugo Benichi9c58a112016-07-06 22:53:17 +09002868 synchronized(sCallbacks) {
Hugo Benichi31c176d2017-06-17 13:14:12 +09002869 if (callback.networkRequest != null
2870 && callback.networkRequest != ALREADY_UNREGISTERED) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09002871 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
2872 // and requests (http://b/20701525).
2873 Log.e(TAG, "NetworkCallback was already registered");
2874 }
Hugo Benichi1e19aef2016-07-07 10:15:56 +09002875 Messenger messenger = new Messenger(handler);
Hugo Benichi9c58a112016-07-06 22:53:17 +09002876 Binder binder = new Binder();
Paul Jensen7221cc32014-06-27 11:05:32 -04002877 if (action == LISTEN) {
Hugo Benichi9c58a112016-07-06 22:53:17 +09002878 request = mService.listenForNetwork(need, messenger, binder);
Paul Jensen7221cc32014-06-27 11:05:32 -04002879 } else {
Hugo Benichi9c58a112016-07-06 22:53:17 +09002880 request = mService.requestNetwork(
2881 need, messenger, timeoutMs, binder, legacyType);
Paul Jensen7221cc32014-06-27 11:05:32 -04002882 }
Hugo Benichi9c58a112016-07-06 22:53:17 +09002883 if (request != null) {
Hugo Benichi1e19aef2016-07-07 10:15:56 +09002884 sCallbacks.put(request, callback);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002885 }
Hugo Benichi1e19aef2016-07-07 10:15:56 +09002886 callback.networkRequest = request;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002887 }
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002888 } catch (RemoteException e) {
2889 throw e.rethrowFromSystemServer();
Hugo Benichicb883232017-05-11 13:16:17 +09002890 } catch (ServiceSpecificException e) {
2891 throw convertServiceException(e);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002892 }
Hugo Benichi9c58a112016-07-06 22:53:17 +09002893 return request;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002894 }
2895
2896 /**
Erik Klinea2d29402016-03-16 15:31:39 +09002897 * Helper function to request a network with a particular legacy type.
Lorenzo Colitti7de289f2015-11-25 12:00:52 +09002898 *
2899 * This is temporarily public @hide so it can be called by system code that uses the
2900 * NetworkRequest API to request networks but relies on CONNECTIVITY_ACTION broadcasts for
2901 * instead network notifications.
2902 *
2903 * TODO: update said system code to rely on NetworkCallbacks and make this method private.
2904 *
2905 * @hide
2906 */
Lorenzo Colittid1179462015-11-25 15:47:14 +09002907 public void requestNetwork(NetworkRequest request, NetworkCallback networkCallback,
Hugo Benichi2583ef02017-02-02 17:02:36 +09002908 int timeoutMs, int legacyType, Handler handler) {
2909 CallbackHandler cbHandler = new CallbackHandler(handler);
2910 NetworkCapabilities nc = request.networkCapabilities;
2911 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
Lorenzo Colitti7de289f2015-11-25 12:00:52 +09002912 }
2913
2914 /**
Lorenzo Colittie285b432015-04-23 15:32:42 +09002915 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002916 *
2917 * This {@link NetworkRequest} will live until released via
Etan Cohenaebf17e2017-03-01 12:47:28 -08002918 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits. A
2919 * version of the method which takes a timeout is
Hugo Benichi0eec03f2017-05-15 15:15:33 +09002920 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002921 * Status of the request can be followed by listening to the various
Robert Greenwalt6078b502014-06-11 16:05:07 -07002922 * callbacks described in {@link NetworkCallback}. The {@link Network}
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002923 * can be used to direct traffic to the network.
Paul Jensenbb2e0e92015-06-16 15:11:58 -04002924 * <p>It is presently unsupported to request a network with mutable
2925 * {@link NetworkCapabilities} such as
2926 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
2927 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
2928 * as these {@code NetworkCapabilities} represent states that a particular
2929 * network may never attain, and whether a network will attain these states
2930 * is unknown prior to bringing up the network so the framework does not
2931 * know how to go about satisfing a request with these capabilities.
Lorenzo Colittid5427052015-10-15 16:29:00 +09002932 *
2933 * <p>This method requires the caller to hold either the
2934 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2935 * or the ability to modify system settings as determined by
2936 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt9258c642014-03-26 16:47:06 -07002937 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07002938 * @param request {@link NetworkRequest} describing this request.
Hugo Benichi2583ef02017-02-02 17:02:36 +09002939 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
2940 * the callback must not be shared - it uniquely specifies this request.
2941 * The callback is invoked on the default internal Handler.
Paul Jensenbb2e0e92015-06-16 15:11:58 -04002942 * @throws IllegalArgumentException if {@code request} specifies any mutable
2943 * {@code NetworkCapabilities}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002944 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07002945 public void requestNetwork(NetworkRequest request, NetworkCallback networkCallback) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09002946 requestNetwork(request, networkCallback, getDefaultHandler());
2947 }
2948
2949 /**
2950 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
2951 *
2952 * This {@link NetworkRequest} will live until released via
Etan Cohenaebf17e2017-03-01 12:47:28 -08002953 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits. A
2954 * version of the method which takes a timeout is
Hugo Benichi0eec03f2017-05-15 15:15:33 +09002955 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}.
Hugo Benichi2583ef02017-02-02 17:02:36 +09002956 * Status of the request can be followed by listening to the various
2957 * callbacks described in {@link NetworkCallback}. The {@link Network}
2958 * can be used to direct traffic to the network.
2959 * <p>It is presently unsupported to request a network with mutable
2960 * {@link NetworkCapabilities} such as
2961 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
2962 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
2963 * as these {@code NetworkCapabilities} represent states that a particular
2964 * network may never attain, and whether a network will attain these states
2965 * is unknown prior to bringing up the network so the framework does not
2966 * know how to go about satisfing a request with these capabilities.
2967 *
2968 * <p>This method requires the caller to hold either the
2969 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2970 * or the ability to modify system settings as determined by
2971 * {@link android.provider.Settings.System#canWrite}.</p>
2972 *
2973 * @param request {@link NetworkRequest} describing this request.
2974 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
2975 * the callback must not be shared - it uniquely specifies this request.
2976 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
2977 * @throws IllegalArgumentException if {@code request} specifies any mutable
2978 * {@code NetworkCapabilities}.
Hugo Benichi2583ef02017-02-02 17:02:36 +09002979 */
2980 public void requestNetwork(
2981 NetworkRequest request, NetworkCallback networkCallback, Handler handler) {
2982 int legacyType = inferLegacyTypeForNetworkCapabilities(request.networkCapabilities);
2983 CallbackHandler cbHandler = new CallbackHandler(handler);
2984 requestNetwork(request, networkCallback, 0, legacyType, cbHandler);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002985 }
2986
2987 /**
Etan Cohenaebf17e2017-03-01 12:47:28 -08002988 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
2989 * by a timeout.
2990 *
2991 * This function behaves identically to the non-timed-out version
2992 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
2993 * is not found within the given time (in milliseconds) the
2994 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
2995 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
2996 * not have to be released if timed-out (it is automatically released). Unregistering a
2997 * request that timed out is not an error.
2998 *
2999 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
3000 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
3001 * for that purpose. Calling this method will attempt to bring up the requested network.
3002 *
3003 * <p>This method requires the caller to hold either the
3004 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3005 * or the ability to modify system settings as determined by
3006 * {@link android.provider.Settings.System#canWrite}.</p>
3007 *
3008 * @param request {@link NetworkRequest} describing this request.
Hugo Benichi0eec03f2017-05-15 15:15:33 +09003009 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3010 * the callback must not be shared - it uniquely specifies this request.
Etan Cohenaebf17e2017-03-01 12:47:28 -08003011 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3012 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3013 * be a positive value (i.e. >0).
Etan Cohenaebf17e2017-03-01 12:47:28 -08003014 */
Hugo Benichi0eec03f2017-05-15 15:15:33 +09003015 public void requestNetwork(NetworkRequest request, NetworkCallback networkCallback,
3016 int timeoutMs) {
Hugo Benichie7678512017-05-09 15:19:01 +09003017 checkTimeout(timeoutMs);
Hugo Benichi2583ef02017-02-02 17:02:36 +09003018 int legacyType = inferLegacyTypeForNetworkCapabilities(request.networkCapabilities);
Erik Klineb583b032017-02-22 12:58:24 +09003019 requestNetwork(request, networkCallback, timeoutMs, legacyType, getDefaultHandler());
Hugo Benichi2583ef02017-02-02 17:02:36 +09003020 }
3021
Hugo Benichi2583ef02017-02-02 17:02:36 +09003022 /**
3023 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
3024 * by a timeout.
3025 *
3026 * This function behaves identically to the non-timedout version, but if a suitable
3027 * network is not found within the given time (in milliseconds) the
Etan Cohenaebf17e2017-03-01 12:47:28 -08003028 * {@link NetworkCallback#onUnavailable} callback is called. The request can still be
3029 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
3030 * not have to be released if timed-out (it is automatically released). Unregistering a
3031 * request that timed out is not an error.
3032 *
3033 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
3034 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
3035 * for that purpose. Calling this method will attempt to bring up the requested network.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003036 *
3037 * <p>This method requires the caller to hold either the
3038 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3039 * or the ability to modify system settings as determined by
3040 * {@link android.provider.Settings.System#canWrite}.</p>
3041 *
3042 * @param request {@link NetworkRequest} describing this request.
Etan Cohenaebf17e2017-03-01 12:47:28 -08003043 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3044 * the callback must not be shared - it uniquely specifies this request.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003045 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichi0eec03f2017-05-15 15:15:33 +09003046 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3047 * before {@link NetworkCallback#onUnavailable} is called.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003048 */
Hugo Benichi0eec03f2017-05-15 15:15:33 +09003049 public void requestNetwork(NetworkRequest request, NetworkCallback networkCallback,
3050 Handler handler, int timeoutMs) {
Hugo Benichie7678512017-05-09 15:19:01 +09003051 checkTimeout(timeoutMs);
Hugo Benichi2583ef02017-02-02 17:02:36 +09003052 int legacyType = inferLegacyTypeForNetworkCapabilities(request.networkCapabilities);
3053 CallbackHandler cbHandler = new CallbackHandler(handler);
3054 requestNetwork(request, networkCallback, timeoutMs, legacyType, cbHandler);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003055 }
3056
3057 /**
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003058 * The lookup key for a {@link Network} object included with the intent after
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003059 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003060 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeremy Joslinfcde58f2015-02-11 16:51:13 -08003061 * <p>
Paul Jensen72db88e2015-03-10 10:54:12 -04003062 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
3063 * then you must get a ConnectivityManager instance before doing so.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003064 */
Erik Kline90e93072014-11-19 12:12:24 +09003065 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003066
3067 /**
Robert Greenwalt6078b502014-06-11 16:05:07 -07003068 * The lookup key for a {@link NetworkRequest} object included with the intent after
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003069 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003070 * {@link android.content.Intent#getParcelableExtra(String)}.
3071 */
Erik Kline90e93072014-11-19 12:12:24 +09003072 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003073
3074
3075 /**
Lorenzo Colittie285b432015-04-23 15:32:42 +09003076 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003077 *
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003078 * This function behaves identically to the version that takes a NetworkCallback, but instead
Robert Greenwalt6078b502014-06-11 16:05:07 -07003079 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003080 * the request may outlive the calling application and get called back when a suitable
3081 * network is found.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003082 * <p>
3083 * The operation is an Intent broadcast that goes to a broadcast receiver that
3084 * you registered with {@link Context#registerReceiver} or through the
3085 * &lt;receiver&gt; tag in an AndroidManifest.xml file
3086 * <p>
3087 * The operation Intent is delivered with two extras, a {@link Network} typed
Erik Kline90e93072014-11-19 12:12:24 +09003088 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
3089 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
Robert Greenwalt9258c642014-03-26 16:47:06 -07003090 * the original requests parameters. It is important to create a new,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003091 * {@link NetworkCallback} based request before completing the processing of the
Robert Greenwalt9258c642014-03-26 16:47:06 -07003092 * Intent to reserve the network or it will be released shortly after the Intent
3093 * is processed.
3094 * <p>
Paul Jensen694f2b82015-06-17 14:15:39 -04003095 * If there is already a request for this Intent registered (with the equality of
Robert Greenwalt9258c642014-03-26 16:47:06 -07003096 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003097 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003098 * <p>
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003099 * The request may be released normally by calling
3100 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003101 * <p>It is presently unsupported to request a network with either
3102 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3103 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3104 * as these {@code NetworkCapabilities} represent states that a particular
3105 * network may never attain, and whether a network will attain these states
3106 * is unknown prior to bringing up the network so the framework does not
3107 * know how to go about satisfing a request with these capabilities.
Lorenzo Colittid5427052015-10-15 16:29:00 +09003108 *
3109 * <p>This method requires the caller to hold either the
3110 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3111 * or the ability to modify system settings as determined by
3112 * {@link android.provider.Settings.System#canWrite}.</p>
3113 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07003114 * @param request {@link NetworkRequest} describing this request.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003115 * @param operation Action to perform when the network is available (corresponds
Robert Greenwalt6078b502014-06-11 16:05:07 -07003116 * to the {@link NetworkCallback#onAvailable} call. Typically
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003117 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003118 * @throws IllegalArgumentException if {@code request} contains either
3119 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3120 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003121 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07003122 public void requestNetwork(NetworkRequest request, PendingIntent operation) {
Hugo Benichie7678512017-05-09 15:19:01 +09003123 checkPendingIntentNotNull(operation);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003124 try {
Robert Greenwalt6078b502014-06-11 16:05:07 -07003125 mService.pendingRequestForNetwork(request.networkCapabilities, operation);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003126 } catch (RemoteException e) {
3127 throw e.rethrowFromSystemServer();
Hugo Benichicb883232017-05-11 13:16:17 +09003128 } catch (ServiceSpecificException e) {
3129 throw convertServiceException(e);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003130 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003131 }
3132
3133 /**
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003134 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
3135 * <p>
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09003136 * This method has the same behavior as
3137 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003138 * releasing network resources and disconnecting.
3139 *
3140 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
3141 * PendingIntent passed to
3142 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
3143 * corresponding NetworkRequest you'd like to remove. Cannot be null.
3144 */
3145 public void releaseNetworkRequest(PendingIntent operation) {
Hugo Benichie7678512017-05-09 15:19:01 +09003146 checkPendingIntentNotNull(operation);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003147 try {
3148 mService.releasePendingNetworkRequest(operation);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003149 } catch (RemoteException e) {
3150 throw e.rethrowFromSystemServer();
3151 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003152 }
3153
Hugo Benichie7678512017-05-09 15:19:01 +09003154 private static void checkPendingIntentNotNull(PendingIntent intent) {
3155 Preconditions.checkNotNull(intent, "PendingIntent cannot be null.");
3156 }
3157
3158 private static void checkCallbackNotNull(NetworkCallback callback) {
3159 Preconditions.checkNotNull(callback, "null NetworkCallback");
3160 }
3161
3162 private static void checkTimeout(int timeoutMs) {
3163 Preconditions.checkArgumentPositive(timeoutMs, "timeoutMs must be strictly positive.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003164 }
3165
3166 /**
Robert Greenwalt9258c642014-03-26 16:47:06 -07003167 * Registers to receive notifications about all networks which satisfy the given
Robert Greenwalt6078b502014-06-11 16:05:07 -07003168 * {@link NetworkRequest}. The callbacks will continue to be called until
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09003169 * either the application exits or link #unregisterNetworkCallback(NetworkCallback)} is called.
Paul Jensenb2748922015-05-06 11:10:18 -04003170 * <p>This method requires the caller to hold the permission
3171 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003172 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07003173 * @param request {@link NetworkRequest} describing this request.
3174 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
3175 * networks change state.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003176 * The callback is invoked on the default internal Handler.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003177 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07003178 public void registerNetworkCallback(NetworkRequest request, NetworkCallback networkCallback) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003179 registerNetworkCallback(request, networkCallback, getDefaultHandler());
3180 }
3181
3182 /**
3183 * Registers to receive notifications about all networks which satisfy the given
3184 * {@link NetworkRequest}. The callbacks will continue to be called until
3185 * either the application exits or link #unregisterNetworkCallback(NetworkCallback)} is called.
3186 * <p>This method requires the caller to hold the permission
3187 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
3188 *
3189 * @param request {@link NetworkRequest} describing this request.
3190 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
3191 * networks change state.
3192 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003193 */
3194 public void registerNetworkCallback(
3195 NetworkRequest request, NetworkCallback networkCallback, Handler handler) {
3196 CallbackHandler cbHandler = new CallbackHandler(handler);
3197 NetworkCapabilities nc = request.networkCapabilities;
3198 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003199 }
3200
3201 /**
Paul Jensen694f2b82015-06-17 14:15:39 -04003202 * Registers a PendingIntent to be sent when a network is available which satisfies the given
3203 * {@link NetworkRequest}.
3204 *
3205 * This function behaves identically to the version that takes a NetworkCallback, but instead
3206 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
3207 * the request may outlive the calling application and get called back when a suitable
3208 * network is found.
3209 * <p>
3210 * The operation is an Intent broadcast that goes to a broadcast receiver that
3211 * you registered with {@link Context#registerReceiver} or through the
3212 * &lt;receiver&gt; tag in an AndroidManifest.xml file
3213 * <p>
3214 * The operation Intent is delivered with two extras, a {@link Network} typed
3215 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
3216 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
3217 * the original requests parameters.
3218 * <p>
3219 * If there is already a request for this Intent registered (with the equality of
3220 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
3221 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
3222 * <p>
3223 * The request may be released normally by calling
Paul Jensenf2c1cfe2015-06-30 14:29:18 -04003224 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
Paul Jensen694f2b82015-06-17 14:15:39 -04003225 * <p>This method requires the caller to hold the permission
3226 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
3227 * @param request {@link NetworkRequest} describing this request.
3228 * @param operation Action to perform when the network is available (corresponds
3229 * to the {@link NetworkCallback#onAvailable} call. Typically
3230 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
3231 */
3232 public void registerNetworkCallback(NetworkRequest request, PendingIntent operation) {
Hugo Benichie7678512017-05-09 15:19:01 +09003233 checkPendingIntentNotNull(operation);
Paul Jensen694f2b82015-06-17 14:15:39 -04003234 try {
3235 mService.pendingListenForNetwork(request.networkCapabilities, operation);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003236 } catch (RemoteException e) {
3237 throw e.rethrowFromSystemServer();
Hugo Benichicb883232017-05-11 13:16:17 +09003238 } catch (ServiceSpecificException e) {
3239 throw convertServiceException(e);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003240 }
Paul Jensen694f2b82015-06-17 14:15:39 -04003241 }
3242
3243 /**
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09003244 * Registers to receive notifications about changes in the system default network. The callbacks
3245 * will continue to be called until either the application exits or
3246 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Erik Klinea2d29402016-03-16 15:31:39 +09003247 * <p>This method requires the caller to hold the permission
3248 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
3249 *
3250 * @param networkCallback The {@link NetworkCallback} that the system will call as the
3251 * system default network changes.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003252 * The callback is invoked on the default internal Handler.
Erik Klinea2d29402016-03-16 15:31:39 +09003253 */
3254 public void registerDefaultNetworkCallback(NetworkCallback networkCallback) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003255 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
3256 }
3257
3258 /**
3259 * Registers to receive notifications about changes in the system default network. The callbacks
3260 * will continue to be called until either the application exits or
3261 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
3262 * <p>This method requires the caller to hold the permission
3263 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
3264 *
3265 * @param networkCallback The {@link NetworkCallback} that the system will call as the
3266 * system default network changes.
3267 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003268 */
3269 public void registerDefaultNetworkCallback(NetworkCallback networkCallback, Handler handler) {
Erik Klinea2d29402016-03-16 15:31:39 +09003270 // This works because if the NetworkCapabilities are null,
3271 // ConnectivityService takes them from the default request.
3272 //
3273 // Since the capabilities are exactly the same as the default request's
3274 // capabilities, this request is guaranteed, at all times, to be
3275 // satisfied by the same network, if any, that satisfies the default
3276 // request, i.e., the system default network.
Hugo Benichie7678512017-05-09 15:19:01 +09003277 NetworkCapabilities nullCapabilities = null;
Hugo Benichi2583ef02017-02-02 17:02:36 +09003278 CallbackHandler cbHandler = new CallbackHandler(handler);
Hugo Benichie7678512017-05-09 15:19:01 +09003279 sendRequestForNetwork(nullCapabilities, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
Erik Klinea2d29402016-03-16 15:31:39 +09003280 }
3281
3282 /**
fengludb571472015-04-21 17:12:05 -07003283 * Requests bandwidth update for a given {@link Network} and returns whether the update request
3284 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
3285 * network connection for updated bandwidth information. The caller will be notified via
3286 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09003287 * method assumes that the caller has previously called
3288 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
3289 * changes.
fenglub15e72b2015-03-20 11:29:56 -07003290 *
fengluae519192015-04-27 14:28:04 -07003291 * @param network {@link Network} specifying which network you're interested.
fengludb571472015-04-21 17:12:05 -07003292 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
fenglub15e72b2015-03-20 11:29:56 -07003293 */
fengludb571472015-04-21 17:12:05 -07003294 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07003295 try {
fengludb571472015-04-21 17:12:05 -07003296 return mService.requestBandwidthUpdate(network);
fenglub15e72b2015-03-20 11:29:56 -07003297 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003298 throw e.rethrowFromSystemServer();
fenglub15e72b2015-03-20 11:29:56 -07003299 }
3300 }
3301
3302 /**
Hugo Benichidafed3d2017-03-06 09:17:06 +09003303 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09003304 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
3305 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
3306 * If the given {@code NetworkCallback} had previously been used with
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +09003307 * {@code #requestNetwork}, any networks that had been connected to only to satisfy that request
3308 * will be disconnected.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003309 *
Hugo Benichidafed3d2017-03-06 09:17:06 +09003310 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
3311 * triggering it as soon as this call returns.
3312 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07003313 * @param networkCallback The {@link NetworkCallback} used when making the request.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003314 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07003315 public void unregisterNetworkCallback(NetworkCallback networkCallback) {
Hugo Benichie7678512017-05-09 15:19:01 +09003316 checkCallbackNotNull(networkCallback);
Hugo Benichidafed3d2017-03-06 09:17:06 +09003317 final List<NetworkRequest> reqs = new ArrayList<>();
3318 // Find all requests associated to this callback and stop callback triggers immediately.
3319 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
3320 synchronized (sCallbacks) {
Hugo Benichi31c176d2017-06-17 13:14:12 +09003321 Preconditions.checkArgument(networkCallback.networkRequest != null,
3322 "NetworkCallback was not registered");
3323 Preconditions.checkArgument(networkCallback.networkRequest != ALREADY_UNREGISTERED,
3324 "NetworkCallback was already unregistered");
Hugo Benichidafed3d2017-03-06 09:17:06 +09003325 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
3326 if (e.getValue() == networkCallback) {
3327 reqs.add(e.getKey());
3328 }
3329 }
3330 // TODO: throw exception if callback was registered more than once (http://b/20701525).
3331 for (NetworkRequest r : reqs) {
3332 try {
3333 mService.releaseNetworkRequest(r);
3334 } catch (RemoteException e) {
3335 throw e.rethrowFromSystemServer();
3336 }
3337 // Only remove mapping if rpc was successful.
3338 sCallbacks.remove(r);
3339 }
Hugo Benichi31c176d2017-06-17 13:14:12 +09003340 networkCallback.networkRequest = ALREADY_UNREGISTERED;
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003341 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003342 }
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04003343
3344 /**
Paul Jensenf2c1cfe2015-06-30 14:29:18 -04003345 * Unregisters a callback previously registered via
3346 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
3347 *
3348 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
3349 * PendingIntent passed to
3350 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
3351 * Cannot be null.
3352 */
3353 public void unregisterNetworkCallback(PendingIntent operation) {
Hugo Benichie7678512017-05-09 15:19:01 +09003354 checkPendingIntentNotNull(operation);
Paul Jensenf2c1cfe2015-06-30 14:29:18 -04003355 releaseNetworkRequest(operation);
3356 }
3357
3358 /**
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003359 * Informs the system whether it should switch to {@code network} regardless of whether it is
3360 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
3361 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
3362 * the system default network regardless of any other network that's currently connected. If
3363 * {@code always} is true, then the choice is remembered, so that the next time the user
3364 * connects to this network, the system will switch to it.
3365 *
3366 * <p>This method requires the caller to hold the permission
3367 * {@link android.Manifest.permission#CONNECTIVITY_INTERNAL}
3368 *
3369 * @param network The network to accept.
3370 * @param accept Whether to accept the network even if unvalidated.
3371 * @param always Whether to remember this choice in the future.
3372 *
3373 * @hide
3374 */
3375 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
3376 try {
3377 mService.setAcceptUnvalidated(network, accept, always);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003378 } catch (RemoteException e) {
3379 throw e.rethrowFromSystemServer();
3380 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003381 }
3382
3383 /**
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003384 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
3385 * only meaningful if the system is configured not to penalize such networks, e.g., if the
3386 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
3387 * NETWORK_AVOID_BAD_WIFI setting is unset}.
3388 *
3389 * <p>This method requires the caller to hold the permission
3390 * {@link android.Manifest.permission#CONNECTIVITY_INTERNAL}
3391 *
3392 * @param network The network to accept.
3393 *
3394 * @hide
3395 */
3396 public void setAvoidUnvalidated(Network network) {
3397 try {
3398 mService.setAvoidUnvalidated(network);
3399 } catch (RemoteException e) {
3400 throw e.rethrowFromSystemServer();
3401 }
3402 }
3403
3404 /**
Lorenzo Colitti2965d332017-04-27 14:30:21 +09003405 * Requests that the system open the captive portal app on the specified network.
3406 *
3407 * @param network The network to log into.
3408 *
3409 * @hide
3410 */
3411 @RequiresPermission(android.Manifest.permission.CONNECTIVITY_INTERNAL)
3412 public void startCaptivePortalApp(Network network) {
3413 try {
3414 mService.startCaptivePortalApp(network);
3415 } catch (RemoteException e) {
3416 throw e.rethrowFromSystemServer();
3417 }
3418 }
3419
3420 /**
Lorenzo Colitti46aa9c02017-01-24 18:08:41 +09003421 * It is acceptable to briefly use multipath data to provide seamless connectivity for
3422 * time-sensitive user-facing operations when the system default network is temporarily
Hugo Benichi0eec03f2017-05-15 15:15:33 +09003423 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
3424 * this method), and the operation should be infrequent to ensure that data usage is limited.
Lorenzo Colitti46aa9c02017-01-24 18:08:41 +09003425 *
3426 * An example of such an operation might be a time-sensitive foreground activity, such as a
3427 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
3428 */
3429 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
3430
3431 /**
3432 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
3433 * a backup channel for traffic that is primarily going over another network.
3434 *
3435 * An example might be maintaining backup connections to peers or servers for the purpose of
3436 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
3437 * on backup paths should be negligible compared to the traffic on the main path.
3438 */
3439 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
3440
3441 /**
3442 * It is acceptable to use metered data to improve network latency and performance.
3443 */
3444 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
3445
3446 /**
3447 * Return value to use for unmetered networks. On such networks we currently set all the flags
3448 * to true.
3449 * @hide
3450 */
3451 public static final int MULTIPATH_PREFERENCE_UNMETERED =
3452 MULTIPATH_PREFERENCE_HANDOVER |
3453 MULTIPATH_PREFERENCE_RELIABILITY |
3454 MULTIPATH_PREFERENCE_PERFORMANCE;
3455
3456 /** @hide */
3457 @Retention(RetentionPolicy.SOURCE)
3458 @IntDef(flag = true, value = {
3459 MULTIPATH_PREFERENCE_HANDOVER,
3460 MULTIPATH_PREFERENCE_RELIABILITY,
3461 MULTIPATH_PREFERENCE_PERFORMANCE,
3462 })
3463 public @interface MultipathPreference {
3464 }
3465
3466 /**
3467 * Provides a hint to the calling application on whether it is desirable to use the
3468 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
3469 * for multipath data transfer on this network when it is not the system default network.
3470 * Applications desiring to use multipath network protocols should call this method before
3471 * each such operation.
3472 * <p>
3473 * This method requires the caller to hold the permission
3474 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
3475 *
3476 * @param network The network on which the application desires to use multipath data.
3477 * If {@code null}, this method will return the a preference that will generally
3478 * apply to metered networks.
3479 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
3480 */
3481 public @MultipathPreference int getMultipathPreference(Network network) {
3482 try {
3483 return mService.getMultipathPreference(network);
3484 } catch (RemoteException e) {
3485 throw e.rethrowFromSystemServer();
3486 }
3487 }
3488
3489 /**
Stuart Scott984dc852015-03-30 13:17:11 -07003490 * Resets all connectivity manager settings back to factory defaults.
3491 * @hide
3492 */
3493 public void factoryReset() {
Stuart Scott984dc852015-03-30 13:17:11 -07003494 try {
Stuart Scottf1fb3972015-04-02 18:00:02 -07003495 mService.factoryReset();
Stuart Scott984dc852015-03-30 13:17:11 -07003496 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003497 throw e.rethrowFromSystemServer();
Stuart Scott984dc852015-03-30 13:17:11 -07003498 }
3499 }
3500
3501 /**
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04003502 * Binds the current process to {@code network}. All Sockets created in the future
3503 * (and not explicitly bound via a bound SocketFactory from
3504 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
3505 * {@code network}. All host name resolutions will be limited to {@code network} as well.
3506 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
3507 * work and all host name resolutions will fail. This is by design so an application doesn't
3508 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
3509 * To clear binding pass {@code null} for {@code network}. Using individually bound
3510 * Sockets created by Network.getSocketFactory().createSocket() and
3511 * performing network-specific host name resolutions via
3512 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
Paul Jensen72db88e2015-03-10 10:54:12 -04003513 * {@code bindProcessToNetwork}.
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04003514 *
3515 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
3516 * the current binding.
3517 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
3518 */
Paul Jensen72db88e2015-03-10 10:54:12 -04003519 public boolean bindProcessToNetwork(Network network) {
3520 // Forcing callers to call thru non-static function ensures ConnectivityManager
3521 // instantiated.
3522 return setProcessDefaultNetwork(network);
3523 }
3524
3525 /**
3526 * Binds the current process to {@code network}. All Sockets created in the future
3527 * (and not explicitly bound via a bound SocketFactory from
3528 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
3529 * {@code network}. All host name resolutions will be limited to {@code network} as well.
3530 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
3531 * work and all host name resolutions will fail. This is by design so an application doesn't
3532 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
3533 * To clear binding pass {@code null} for {@code network}. Using individually bound
3534 * Sockets created by Network.getSocketFactory().createSocket() and
3535 * performing network-specific host name resolutions via
3536 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
3537 * {@code setProcessDefaultNetwork}.
3538 *
3539 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
3540 * the current binding.
3541 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
3542 * @deprecated This function can throw {@link IllegalStateException}. Use
3543 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
3544 * is a direct replacement.
3545 */
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04003546 public static boolean setProcessDefaultNetwork(Network network) {
Paul Jensenc91b5342014-08-27 12:38:45 -04003547 int netId = (network == null) ? NETID_UNSET : network.netId;
Paul Jensen72db88e2015-03-10 10:54:12 -04003548 if (netId == NetworkUtils.getBoundNetworkForProcess()) {
Paul Jensenc91b5342014-08-27 12:38:45 -04003549 return true;
3550 }
3551 if (NetworkUtils.bindProcessToNetwork(netId)) {
Paul Jensene0bef712014-12-10 15:12:18 -05003552 // Set HTTP proxy system properties to match network.
3553 // TODO: Deprecate this static method and replace it with a non-static version.
Lorenzo Colittiec4c5552015-04-22 11:52:48 +09003554 try {
3555 Proxy.setHttpProxySystemProperty(getInstance().getDefaultProxy());
3556 } catch (SecurityException e) {
3557 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
3558 Log.e(TAG, "Can't set proxy properties", e);
3559 }
Paul Jensenc91b5342014-08-27 12:38:45 -04003560 // Must flush DNS cache as new network may have different DNS resolutions.
3561 InetAddress.clearDnsCache();
3562 // Must flush socket pool as idle sockets will be bound to previous network and may
3563 // cause subsequent fetches to be performed on old network.
3564 NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
3565 return true;
3566 } else {
3567 return false;
3568 }
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04003569 }
3570
3571 /**
3572 * Returns the {@link Network} currently bound to this process via
Paul Jensen72db88e2015-03-10 10:54:12 -04003573 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04003574 *
3575 * @return {@code Network} to which this process is bound, or {@code null}.
3576 */
Paul Jensen72db88e2015-03-10 10:54:12 -04003577 public Network getBoundNetworkForProcess() {
3578 // Forcing callers to call thru non-static function ensures ConnectivityManager
3579 // instantiated.
3580 return getProcessDefaultNetwork();
3581 }
3582
3583 /**
3584 * Returns the {@link Network} currently bound to this process via
3585 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
3586 *
3587 * @return {@code Network} to which this process is bound, or {@code null}.
3588 * @deprecated Using this function can lead to other functions throwing
3589 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
3590 * {@code getBoundNetworkForProcess} is a direct replacement.
3591 */
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04003592 public static Network getProcessDefaultNetwork() {
Paul Jensen72db88e2015-03-10 10:54:12 -04003593 int netId = NetworkUtils.getBoundNetworkForProcess();
Paul Jensenbcc76d32014-07-11 08:17:29 -04003594 if (netId == NETID_UNSET) return null;
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04003595 return new Network(netId);
3596 }
3597
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09003598 private void unsupportedStartingFrom(int version) {
3599 if (Process.myUid() == Process.SYSTEM_UID) {
3600 // The getApplicationInfo() call we make below is not supported in system context, and
3601 // we want to allow the system to use these APIs anyway.
3602 return;
3603 }
3604
3605 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
3606 throw new UnsupportedOperationException(
3607 "This method is not supported in target SDK version " + version + " and above");
3608 }
3609 }
3610
3611 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
3612 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
Lifu Tang30f95a72016-01-07 23:20:38 -08003613 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09003614 // remove these exemptions. Note that this check is not secure, and apps can still access these
3615 // functions by accessing ConnectivityService directly. However, it should be clear that doing
3616 // so is unsupported and may break in the future. http://b/22728205
3617 private void checkLegacyRoutingApiAccess() {
3618 if (mContext.checkCallingOrSelfPermission("com.android.permission.INJECT_OMADM_SETTINGS")
3619 == PackageManager.PERMISSION_GRANTED) {
3620 return;
3621 }
3622
Dianne Hackborn692a2442015-07-31 10:35:34 -07003623 unsupportedStartingFrom(VERSION_CODES.M);
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09003624 }
3625
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04003626 /**
3627 * Binds host resolutions performed by this process to {@code network}.
Paul Jensen72db88e2015-03-10 10:54:12 -04003628 * {@link #bindProcessToNetwork} takes precedence over this setting.
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04003629 *
3630 * @param network The {@link Network} to bind host resolutions from the current process to, or
3631 * {@code null} to clear the current binding.
3632 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
3633 * @hide
3634 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
3635 */
3636 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
Paul Jensenbcc76d32014-07-11 08:17:29 -04003637 return NetworkUtils.bindProcessToNetworkForHostResolution(
3638 network == null ? NETID_UNSET : network.netId);
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04003639 }
Felipe Leme1b103232016-01-22 09:44:57 -08003640
3641 /**
3642 * Device is not restricting metered network activity while application is running on
3643 * background.
3644 */
3645 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
3646
3647 /**
3648 * Device is restricting metered network activity while application is running on background,
3649 * but application is allowed to bypass it.
3650 * <p>
3651 * In this state, application should take action to mitigate metered network access.
3652 * For example, a music streaming application should switch to a low-bandwidth bitrate.
3653 */
3654 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
3655
3656 /**
3657 * Device is restricting metered network activity while application is running on background.
Felipe Leme9778f762016-01-27 14:46:39 -08003658 * <p>
Felipe Leme1b103232016-01-22 09:44:57 -08003659 * In this state, application should not try to use the network while running on background,
3660 * because it would be denied.
3661 */
3662 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
3663
Felipe Leme9778f762016-01-27 14:46:39 -08003664 /**
3665 * A change in the background metered network activity restriction has occurred.
3666 * <p>
3667 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
3668 * applies to them.
3669 * <p>
3670 * This is only sent to registered receivers, not manifest receivers.
3671 */
3672 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
3673 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
3674 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
3675
Felipe Lemeecfccea2016-01-25 11:48:04 -08003676 /** @hide */
3677 @Retention(RetentionPolicy.SOURCE)
Felipe Leme1b103232016-01-22 09:44:57 -08003678 @IntDef(flag = false, value = {
3679 RESTRICT_BACKGROUND_STATUS_DISABLED,
3680 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
3681 RESTRICT_BACKGROUND_STATUS_ENABLED,
3682 })
Felipe Leme1b103232016-01-22 09:44:57 -08003683 public @interface RestrictBackgroundStatus {
3684 }
3685
3686 private INetworkPolicyManager getNetworkPolicyManager() {
3687 synchronized (this) {
3688 if (mNPManager != null) {
3689 return mNPManager;
3690 }
3691 mNPManager = INetworkPolicyManager.Stub.asInterface(ServiceManager
3692 .getService(Context.NETWORK_POLICY_SERVICE));
3693 return mNPManager;
3694 }
3695 }
3696
3697 /**
3698 * Determines if the calling application is subject to metered network restrictions while
3699 * running on background.
Felipe Lemec9c7be52016-05-16 13:57:19 -07003700 *
3701 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
3702 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
3703 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
Felipe Leme1b103232016-01-22 09:44:57 -08003704 */
3705 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
3706 try {
3707 return getNetworkPolicyManager().getRestrictBackgroundByCaller();
3708 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003709 throw e.rethrowFromSystemServer();
Felipe Leme1b103232016-01-22 09:44:57 -08003710 }
3711 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003712}