blob: 8b01ed8de35a332276515166fdf331dd9184a0c6 [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;
Jeff Sharkey30e06bb2017-04-24 11:18:03 -060020import 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;
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -060024import android.annotation.SystemService;
Robert Greenwalt9258c642014-03-26 16:47:06 -070025import android.app.PendingIntent;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -070026import android.content.Context;
Robert Greenwaltd19c41c2014-05-18 23:07:25 -070027import android.content.Intent;
Lorenzo Colittiffc42b02015-07-29 11:41:21 +090028import android.content.pm.PackageManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -070029import android.os.Binder;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -070030import android.os.Build.VERSION_CODES;
Jeremy Klein36c7aa02016-01-22 14:11:45 -080031import android.os.Bundle;
Robert Greenwalt9258c642014-03-26 16:47:06 -070032import android.os.Handler;
33import android.os.HandlerThread;
Dianne Hackborn77b987f2014-02-26 16:20:52 -080034import android.os.IBinder;
35import android.os.INetworkActivityListener;
36import android.os.INetworkManagementService;
Robert Greenwalt9258c642014-03-26 16:47:06 -070037import android.os.Looper;
38import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070039import android.os.Messenger;
Lorenzo Colittiffc42b02015-07-29 11:41:21 +090040import android.os.Process;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -080042import android.os.ResultReceiver;
Dianne Hackborn77b987f2014-02-26 16:20:52 -080043import android.os.ServiceManager;
Hugo Benichicb883232017-05-11 13:16:17 +090044import android.os.ServiceSpecificException;
Jeff Sharkey961e3042011-08-29 16:02:57 -070045import android.provider.Settings;
Wink Saville36ffb042014-12-05 11:10:30 -080046import android.telephony.SubscriptionManager;
Dianne Hackborn77b987f2014-02-26 16:20:52 -080047import android.util.ArrayMap;
Robert Greenwalt9258c642014-03-26 16:47:06 -070048import android.util.Log;
Erik Kline35bf06c2017-01-26 18:08:28 +090049import android.util.SparseIntArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050
Robert Greenwaltafa05c02014-05-21 20:04:36 -070051import com.android.internal.telephony.ITelephony;
Robert Greenwalt562cc542014-05-15 18:07:26 -070052import com.android.internal.telephony.PhoneConstants;
Hugo Benichidafed3d2017-03-06 09:17:06 +090053import com.android.internal.util.Preconditions;
54import com.android.internal.util.Protocol;
Robert Greenwaltafa05c02014-05-21 20:04:36 -070055
Paul Jensenc91b5342014-08-27 12:38:45 -040056import libcore.net.event.NetworkEventDispatcher;
57
Felipe Leme1b103232016-01-22 09:44:57 -080058import java.lang.annotation.Retention;
59import java.lang.annotation.RetentionPolicy;
Jeremy Kleind42209d2015-12-28 15:11:58 -080060import java.net.InetAddress;
Hugo Benichidafed3d2017-03-06 09:17:06 +090061import java.util.ArrayList;
Jeremy Kleind42209d2015-12-28 15:11:58 -080062import java.util.HashMap;
Hugo Benichidafed3d2017-03-06 09:17:06 +090063import java.util.List;
64import java.util.Map;
Jeremy Kleind42209d2015-12-28 15:11:58 -080065
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066/**
67 * Class that answers queries about the state of network connectivity. It also
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -060068 * notifies applications when network connectivity changes.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069 * <p>
70 * The primary responsibilities of this class are to:
71 * <ol>
72 * <li>Monitor network connections (Wi-Fi, GPRS, UMTS, etc.)</li>
73 * <li>Send broadcast intents when network connectivity changes</li>
74 * <li>Attempt to "fail over" to another network when connectivity to a network
75 * is lost</li>
76 * <li>Provide an API that allows applications to query the coarse-grained or fine-grained
77 * state of the available networks</li>
Robert Greenwaltd19c41c2014-05-18 23:07:25 -070078 * <li>Provide an API that allows applications to request and select networks for their data
79 * traffic</li>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080 * </ol>
81 */
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -060082@SystemService(Context.CONNECTIVITY_SERVICE)
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.
Chalard Jean054cd162018-02-10 05:33:50 +0900115 *
116 * @deprecated apps should use the more versatile {@link #requestNetwork},
117 * {@link #registerNetworkCallback} or {@link #registerDefaultNetworkCallback}
118 * functions instead for faster and more detailed updates about the network
119 * changes they care about.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800120 */
Jeff Sharkey4fa63b22013-02-20 18:21:19 -0800121 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Chalard Jean054cd162018-02-10 05:33:50 +0900122 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123 public static final String CONNECTIVITY_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700124
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800125 /**
Robert Greenwalte94a6ff2015-09-01 08:23:04 -0700126 * A temporary hack until SUPL system can get off the legacy APIS.
127 * They do too many network requests and the long list of apps listening
128 * and waking due to the CONNECTIVITY_ACTION bcast makes it expensive.
129 * Use this bcast intent instead for SUPL requests.
130 * @hide
131 */
132 public static final String CONNECTIVITY_ACTION_SUPL =
133 "android.net.conn.CONNECTIVITY_CHANGE_SUPL";
134
135 /**
Paul Jensen25a217c2015-02-27 22:55:47 -0500136 * The device has connected to a network that has presented a captive
137 * portal, which is blocking Internet connectivity. The user was presented
138 * with a notification that network sign in is required,
139 * and the user invoked the notification's action indicating they
Paul Jensen49e3edf2015-05-22 10:50:39 -0400140 * desire to sign in to the network. Apps handling this activity should
Paul Jensen25a217c2015-02-27 22:55:47 -0500141 * facilitate signing in to the network. This action includes a
142 * {@link Network} typed extra called {@link #EXTRA_NETWORK} that represents
143 * the network presenting the captive portal; all communication with the
144 * captive portal must be done using this {@code Network} object.
145 * <p/>
Paul Jensen49e3edf2015-05-22 10:50:39 -0400146 * This activity includes a {@link CaptivePortal} extra named
147 * {@link #EXTRA_CAPTIVE_PORTAL} that can be used to indicate different
148 * outcomes of the captive portal sign in to the system:
149 * <ul>
150 * <li> When the app handling this action believes the user has signed in to
151 * the network and the captive portal has been dismissed, the app should
152 * call {@link CaptivePortal#reportCaptivePortalDismissed} so the system can
153 * reevaluate the network. If reevaluation finds the network no longer
154 * subject to a captive portal, the network may become the default active
155 * data network. </li>
156 * <li> When the app handling this action believes the user explicitly wants
Paul Jensen25a217c2015-02-27 22:55:47 -0500157 * to ignore the captive portal and the network, the app should call
Paul Jensen49e3edf2015-05-22 10:50:39 -0400158 * {@link CaptivePortal#ignoreNetwork}. </li>
159 * </ul>
Paul Jensen25a217c2015-02-27 22:55:47 -0500160 */
161 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
162 public static final String ACTION_CAPTIVE_PORTAL_SIGN_IN = "android.net.conn.CAPTIVE_PORTAL";
163
164 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800165 * The lookup key for a {@link NetworkInfo} object. Retrieve with
166 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700167 *
168 * @deprecated Since {@link NetworkInfo} can vary based on UID, applications
169 * should always obtain network information through
Paul Jensen3541e9f2015-03-18 12:23:02 -0400170 * {@link #getActiveNetworkInfo()}.
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -0700171 * @see #EXTRA_NETWORK_TYPE
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800172 */
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700173 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800174 public static final String EXTRA_NETWORK_INFO = "networkInfo";
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700175
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800176 /**
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -0700177 * Network type which triggered a {@link #CONNECTIVITY_ACTION} broadcast.
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -0700178 *
179 * @see android.content.Intent#getIntExtra(String, int)
180 */
181 public static final String EXTRA_NETWORK_TYPE = "networkType";
182
183 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800184 * The lookup key for a boolean that indicates whether a connect event
185 * is for a network to which the connectivity manager was failing over
186 * following a disconnect on another network.
187 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
188 */
189 public static final String EXTRA_IS_FAILOVER = "isFailover";
190 /**
191 * The lookup key for a {@link NetworkInfo} object. This is supplied when
192 * there is another network that it may be possible to connect to. Retrieve with
193 * {@link android.content.Intent#getParcelableExtra(String)}.
194 */
195 public static final String EXTRA_OTHER_NETWORK_INFO = "otherNetwork";
196 /**
197 * The lookup key for a boolean that indicates whether there is a
198 * complete lack of connectivity, i.e., no network is available.
199 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
200 */
201 public static final String EXTRA_NO_CONNECTIVITY = "noConnectivity";
202 /**
203 * The lookup key for a string that indicates why an attempt to connect
204 * to a network failed. The string has no particular structure. It is
205 * intended to be used in notifications presented to users. Retrieve
206 * it with {@link android.content.Intent#getStringExtra(String)}.
207 */
208 public static final String EXTRA_REASON = "reason";
209 /**
210 * The lookup key for a string that provides optionally supplied
211 * extra information about the network state. The information
212 * may be passed up from the lower networking layers, and its
213 * meaning may be specific to a particular network type. Retrieve
214 * it with {@link android.content.Intent#getStringExtra(String)}.
215 */
216 public static final String EXTRA_EXTRA_INFO = "extraInfo";
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700217 /**
218 * The lookup key for an int that provides information about
219 * our connection to the internet at large. 0 indicates no connection,
220 * 100 indicates a great connection. Retrieve it with
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700221 * {@link android.content.Intent#getIntExtra(String, int)}.
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700222 * {@hide}
223 */
224 public static final String EXTRA_INET_CONDITION = "inetCondition";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800225 /**
Paul Jensen49e3edf2015-05-22 10:50:39 -0400226 * The lookup key for a {@link CaptivePortal} object included with the
227 * {@link #ACTION_CAPTIVE_PORTAL_SIGN_IN} intent. The {@code CaptivePortal}
228 * object can be used to either indicate to the system that the captive
229 * portal has been dismissed or that the user does not want to pursue
230 * signing in to captive portal. Retrieve it with
231 * {@link android.content.Intent#getParcelableExtra(String)}.
Paul Jensen25a217c2015-02-27 22:55:47 -0500232 */
Paul Jensen49e3edf2015-05-22 10:50:39 -0400233 public static final String EXTRA_CAPTIVE_PORTAL = "android.net.extra.CAPTIVE_PORTAL";
Jan Nordqvist52eb29f2015-09-22 15:54:32 -0700234
235 /**
236 * Key for passing a URL to the captive portal login activity.
237 */
238 public static final String EXTRA_CAPTIVE_PORTAL_URL = "android.net.extra.CAPTIVE_PORTAL_URL";
239
Paul Jensen25a217c2015-02-27 22:55:47 -0500240 /**
Hugo Benichicdf3ba42016-12-14 08:23:40 +0900241 * Key for passing a user agent string to the captive portal login activity.
242 * {@hide}
243 */
244 public static final String EXTRA_CAPTIVE_PORTAL_USER_AGENT =
245 "android.net.extra.CAPTIVE_PORTAL_USER_AGENT";
246
247 /**
Haoyu Baidb3c8672012-06-20 14:29:57 -0700248 * Broadcast action to indicate the change of data activity status
249 * (idle or active) on a network in a recent period.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800250 * The network becomes active when data transmission is started, or
251 * idle if there is no data transmission for a period of time.
Haoyu Baidb3c8672012-06-20 14:29:57 -0700252 * {@hide}
253 */
254 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
255 public static final String ACTION_DATA_ACTIVITY_CHANGE = "android.net.conn.DATA_ACTIVITY_CHANGE";
256 /**
257 * The lookup key for an enum that indicates the network device type on which this data activity
258 * change happens.
259 * {@hide}
260 */
261 public static final String EXTRA_DEVICE_TYPE = "deviceType";
262 /**
263 * The lookup key for a boolean that indicates the device is active or not. {@code true} means
264 * it is actively sending or receiving data and {@code false} means it is idle.
265 * {@hide}
266 */
267 public static final String EXTRA_IS_ACTIVE = "isActive";
Ashish Sharma0535a9f2014-03-12 18:42:23 -0700268 /**
269 * The lookup key for a long that contains the timestamp (nanos) of the radio state change.
270 * {@hide}
271 */
272 public static final String EXTRA_REALTIME_NS = "tsNanos";
Haoyu Baidb3c8672012-06-20 14:29:57 -0700273
274 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800275 * Broadcast Action: The setting for background data usage has changed
276 * values. Use {@link #getBackgroundDataSetting()} to get the current value.
277 * <p>
278 * If an application uses the network in the background, it should listen
279 * for this broadcast and stop using the background data if the value is
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700280 * {@code false}.
Jeff Sharkey54ee2ad2012-01-30 16:29:24 -0800281 * <p>
282 *
283 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability
284 * of background data depends on several combined factors, and
285 * this broadcast is no longer sent. Instead, when background
286 * data is unavailable, {@link #getActiveNetworkInfo()} will now
287 * appear disconnected. During first boot after a platform
288 * upgrade, this broadcast will be sent once if
289 * {@link #getBackgroundDataSetting()} was {@code false} before
290 * the upgrade.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800291 */
292 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Jeff Sharkey54ee2ad2012-01-30 16:29:24 -0800293 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800294 public static final String ACTION_BACKGROUND_DATA_SETTING_CHANGED =
295 "android.net.conn.BACKGROUND_DATA_SETTING_CHANGED";
296
Robert Greenwalt1e9aac22010-09-15 17:36:33 -0700297 /**
298 * Broadcast Action: The network connection may not be good
299 * uses {@code ConnectivityManager.EXTRA_INET_CONDITION} and
300 * {@code ConnectivityManager.EXTRA_NETWORK_INFO} to specify
301 * the network and it's condition.
302 * @hide
303 */
Jeff Sharkey4fa63b22013-02-20 18:21:19 -0800304 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Robert Greenwalt1e9aac22010-09-15 17:36:33 -0700305 public static final String INET_CONDITION_ACTION =
306 "android.net.conn.INET_CONDITION_ACTION";
307
Robert Greenwalt42acef32009-08-12 16:08:25 -0700308 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800309 * Broadcast Action: A tetherable connection has come or gone.
310 * Uses {@code ConnectivityManager.EXTRA_AVAILABLE_TETHER},
Erik Kline8351faa2017-04-17 16:47:23 +0900311 * {@code ConnectivityManager.EXTRA_ACTIVE_LOCAL_ONLY},
312 * {@code ConnectivityManager.EXTRA_ACTIVE_TETHER}, and
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800313 * {@code ConnectivityManager.EXTRA_ERRORED_TETHER} to indicate
314 * the current state of tethering. Each include a list of
315 * interface names in that state (may be empty).
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800316 * @hide
317 */
Jeff Sharkey4fa63b22013-02-20 18:21:19 -0800318 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800319 public static final String ACTION_TETHER_STATE_CHANGED =
320 "android.net.conn.TETHER_STATE_CHANGED";
321
322 /**
323 * @hide
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800324 * gives a String[] listing all the interfaces configured for
325 * tethering and currently available for tethering.
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800326 */
Robert Greenwalt2a091d72010-02-11 18:18:40 -0800327 public static final String EXTRA_AVAILABLE_TETHER = "availableArray";
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800328
329 /**
330 * @hide
Erik Kline8351faa2017-04-17 16:47:23 +0900331 * gives a String[] listing all the interfaces currently in local-only
332 * mode (ie, has DHCPv4+IPv6-ULA support and no packet forwarding)
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800333 */
Erik Kline8351faa2017-04-17 16:47:23 +0900334 public static final String EXTRA_ACTIVE_LOCAL_ONLY = "localOnlyArray";
335
336 /**
337 * @hide
338 * gives a String[] listing all the interfaces currently tethered
339 * (ie, has DHCPv4 support and packets potentially forwarded/NATed)
340 */
341 public static final String EXTRA_ACTIVE_TETHER = "tetherArray";
Robert Greenwalt2a091d72010-02-11 18:18:40 -0800342
343 /**
344 * @hide
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800345 * gives a String[] listing all the interfaces we tried to tether and
346 * failed. Use {@link #getLastTetherError} to find the error code
347 * for any interfaces listed here.
Robert Greenwalt2a091d72010-02-11 18:18:40 -0800348 */
349 public static final String EXTRA_ERRORED_TETHER = "erroredArray";
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800350
351 /**
Russell Brenner108da0c2013-02-12 10:03:14 -0800352 * Broadcast Action: The captive portal tracker has finished its test.
353 * Sent only while running Setup Wizard, in lieu of showing a user
354 * notification.
355 * @hide
356 */
Jeff Sharkey4fa63b22013-02-20 18:21:19 -0800357 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Russell Brenner108da0c2013-02-12 10:03:14 -0800358 public static final String ACTION_CAPTIVE_PORTAL_TEST_COMPLETED =
359 "android.net.conn.CAPTIVE_PORTAL_TEST_COMPLETED";
360 /**
361 * The lookup key for a boolean that indicates whether a captive portal was detected.
362 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
363 * @hide
364 */
365 public static final String EXTRA_IS_CAPTIVE_PORTAL = "captivePortal";
366
367 /**
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900368 * Action used to display a dialog that asks the user whether to connect to a network that is
369 * not validated. This intent is used to start the dialog in settings via startActivity.
370 *
371 * @hide
372 */
373 public static final String ACTION_PROMPT_UNVALIDATED = "android.net.conn.PROMPT_UNVALIDATED";
374
375 /**
Lorenzo Colitti9be58c52016-09-15 14:02:29 +0900376 * Action used to display a dialog that asks the user whether to avoid a network that is no
377 * longer validated. This intent is used to start the dialog in settings via startActivity.
378 *
379 * @hide
380 */
381 public static final String ACTION_PROMPT_LOST_VALIDATION =
382 "android.net.conn.PROMPT_LOST_VALIDATION";
383
384 /**
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800385 * Invalid tethering type.
386 * @see #startTethering(int, OnStartTetheringCallback, boolean)
387 * @hide
388 */
389 public static final int TETHERING_INVALID = -1;
390
391 /**
392 * Wifi tethering type.
393 * @see #startTethering(int, OnStartTetheringCallback, boolean)
394 * @hide
395 */
396 @SystemApi
397 public static final int TETHERING_WIFI = 0;
398
399 /**
400 * USB tethering type.
401 * @see #startTethering(int, OnStartTetheringCallback, boolean)
402 * @hide
403 */
404 @SystemApi
405 public static final int TETHERING_USB = 1;
406
407 /**
408 * Bluetooth tethering type.
409 * @see #startTethering(int, OnStartTetheringCallback, boolean)
410 * @hide
411 */
412 @SystemApi
413 public static final int TETHERING_BLUETOOTH = 2;
414
415 /**
Dedy Lansky4a35bb42017-03-14 13:21:15 +0200416 * WIGIG tethering type. Use a separate type to prevent
417 * conflicts with TETHERING_WIFI
418 * @hide
419 */
420 public static final int TETHERING_WIGIG = 3;
421
422 /**
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800423 * Extra used for communicating with the TetherService. Includes the type of tethering to
424 * enable if any.
425 * @hide
426 */
427 public static final String EXTRA_ADD_TETHER_TYPE = "extraAddTetherType";
428
429 /**
430 * Extra used for communicating with the TetherService. Includes the type of tethering for
431 * which to cancel provisioning.
432 * @hide
433 */
434 public static final String EXTRA_REM_TETHER_TYPE = "extraRemTetherType";
435
436 /**
437 * Extra used for communicating with the TetherService. True to schedule a recheck of tether
438 * provisioning.
439 * @hide
440 */
441 public static final String EXTRA_SET_ALARM = "extraSetAlarm";
442
443 /**
444 * Tells the TetherService to run a provision check now.
445 * @hide
446 */
447 public static final String EXTRA_RUN_PROVISION = "extraRunProvision";
448
449 /**
450 * Extra used for communicating with the TetherService. Contains the {@link ResultReceiver}
451 * which will receive provisioning results. Can be left empty.
452 * @hide
453 */
454 public static final String EXTRA_PROVISION_CALLBACK = "extraProvisionCallback";
455
456 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800457 * The absence of a connection type.
Robert Greenwaltccf83af12011-06-02 17:30:47 -0700458 * @hide
459 */
460 public static final int TYPE_NONE = -1;
461
462 /**
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900463 * A Mobile data connection. Devices may support more than one.
464 *
465 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
466 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
467 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700468 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900469 @Deprecated
Robert Greenwalt42acef32009-08-12 16:08:25 -0700470 public static final int TYPE_MOBILE = 0;
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900471
Robert Greenwalt42acef32009-08-12 16:08:25 -0700472 /**
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900473 * A WIFI data connection. Devices may support more than one.
474 *
475 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
476 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
477 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700478 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900479 @Deprecated
Robert Greenwalt42acef32009-08-12 16:08:25 -0700480 public static final int TYPE_WIFI = 1;
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900481
Robert Greenwalt42acef32009-08-12 16:08:25 -0700482 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800483 * An MMS-specific Mobile data connection. This network type may use the
484 * same network interface as {@link #TYPE_MOBILE} or it may use a different
485 * one. This is used by applications needing to talk to the carrier's
486 * Multimedia Messaging Service servers.
Lorenzo Colittie285b432015-04-23 15:32:42 +0900487 *
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900488 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +0900489 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colittie285b432015-04-23 15:32:42 +0900490 * provides the {@link NetworkCapabilities#NET_CAPABILITY_MMS} capability.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700491 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700492 @Deprecated
Robert Greenwalt42acef32009-08-12 16:08:25 -0700493 public static final int TYPE_MOBILE_MMS = 2;
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900494
Robert Greenwalt42acef32009-08-12 16:08:25 -0700495 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800496 * A SUPL-specific Mobile data connection. This network type may use the
497 * same network interface as {@link #TYPE_MOBILE} or it may use a different
498 * one. This is used by applications needing to talk to the carrier's
499 * Secure User Plane Location servers for help locating the device.
Lorenzo Colittie285b432015-04-23 15:32:42 +0900500 *
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900501 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +0900502 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
Lorenzo Colittie285b432015-04-23 15:32:42 +0900503 * provides the {@link NetworkCapabilities#NET_CAPABILITY_SUPL} capability.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700504 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700505 @Deprecated
Robert Greenwalt42acef32009-08-12 16:08:25 -0700506 public static final int TYPE_MOBILE_SUPL = 3;
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900507
Robert Greenwalt42acef32009-08-12 16:08:25 -0700508 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800509 * A DUN-specific Mobile data connection. This network type may use the
510 * same network interface as {@link #TYPE_MOBILE} or it may use a different
511 * one. This is sometimes by the system when setting up an upstream connection
512 * for tethering so that the carrier is aware of DUN traffic.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900513 *
514 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
515 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
516 * provides the {@link NetworkCapabilities#NET_CAPABILITY_DUN} capability.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700517 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900518 @Deprecated
Robert Greenwalt42acef32009-08-12 16:08:25 -0700519 public static final int TYPE_MOBILE_DUN = 4;
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900520
Robert Greenwalt42acef32009-08-12 16:08:25 -0700521 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800522 * A High Priority Mobile data connection. This network type uses the
523 * same network interface as {@link #TYPE_MOBILE} but the routing setup
Lorenzo Colittie285b432015-04-23 15:32:42 +0900524 * is different.
525 *
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900526 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
527 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
528 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt42acef32009-08-12 16:08:25 -0700529 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700530 @Deprecated
Robert Greenwalt42acef32009-08-12 16:08:25 -0700531 public static final int TYPE_MOBILE_HIPRI = 5;
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900532
jsh8214deb2010-03-11 15:04:43 -0800533 /**
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900534 * A WiMAX data connection.
535 *
536 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
537 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
538 * appropriate network. {@see NetworkCapabilities} for supported transports.
jsh8214deb2010-03-11 15:04:43 -0800539 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900540 @Deprecated
jsh8214deb2010-03-11 15:04:43 -0800541 public static final int TYPE_WIMAX = 6;
Robert Greenwaltda3d5e62010-12-06 13:56:24 -0800542
Jaikumar Ganesh15c74392010-12-21 22:31:44 -0800543 /**
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900544 * A Bluetooth data connection.
545 *
546 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
547 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
548 * appropriate network. {@see NetworkCapabilities} for supported transports.
Jaikumar Ganesh15c74392010-12-21 22:31:44 -0800549 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900550 @Deprecated
Jaikumar Ganesh15c74392010-12-21 22:31:44 -0800551 public static final int TYPE_BLUETOOTH = 7;
552
Robert Greenwalt60810842011-04-22 15:28:18 -0700553 /**
554 * Dummy data connection. This should not be used on shipping devices.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900555 * @deprecated This is not used any more.
Robert Greenwalt60810842011-04-22 15:28:18 -0700556 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900557 @Deprecated
Jaikumar Ganesh15c74392010-12-21 22:31:44 -0800558 public static final int TYPE_DUMMY = 8;
Wink Saville9d7d6282011-03-12 14:52:01 -0800559
Robert Greenwalt60810842011-04-22 15:28:18 -0700560 /**
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900561 * An Ethernet data connection.
562 *
563 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
564 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
565 * appropriate network. {@see NetworkCapabilities} for supported transports.
Robert Greenwalt60810842011-04-22 15:28:18 -0700566 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900567 @Deprecated
Robert Greenwalte12aec92011-01-28 14:48:37 -0800568 public static final int TYPE_ETHERNET = 9;
Robert Greenwalt60810842011-04-22 15:28:18 -0700569
Wink Saville9d7d6282011-03-12 14:52:01 -0800570 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800571 * Over the air Administration.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900572 * @deprecated Use {@link NetworkCapabilities} instead.
Wink Saville9d7d6282011-03-12 14:52:01 -0800573 * {@hide}
574 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900575 @Deprecated
Wink Saville9d7d6282011-03-12 14:52:01 -0800576 public static final int TYPE_MOBILE_FOTA = 10;
577
578 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800579 * IP Multimedia Subsystem.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900580 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IMS} instead.
Wink Saville9d7d6282011-03-12 14:52:01 -0800581 * {@hide}
582 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900583 @Deprecated
Wink Saville9d7d6282011-03-12 14:52:01 -0800584 public static final int TYPE_MOBILE_IMS = 11;
585
586 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800587 * Carrier Branded Services.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900588 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_CBS} instead.
Wink Saville9d7d6282011-03-12 14:52:01 -0800589 * {@hide}
590 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900591 @Deprecated
Wink Saville9d7d6282011-03-12 14:52:01 -0800592 public static final int TYPE_MOBILE_CBS = 12;
593
repo syncaea743a2011-07-29 23:55:49 -0700594 /**
595 * A Wi-Fi p2p connection. Only requesting processes will have access to
596 * the peers connected.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900597 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_WIFI_P2P} instead.
repo syncaea743a2011-07-29 23:55:49 -0700598 * {@hide}
599 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900600 @Deprecated
repo syncaea743a2011-07-29 23:55:49 -0700601 public static final int TYPE_WIFI_P2P = 13;
Wink Saville9d7d6282011-03-12 14:52:01 -0800602
Wink Saville5e56bc52013-07-29 15:00:57 -0700603 /**
604 * The network to use for initially attaching to the network
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900605 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IA} instead.
Wink Saville5e56bc52013-07-29 15:00:57 -0700606 * {@hide}
607 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900608 @Deprecated
Wink Saville5e56bc52013-07-29 15:00:57 -0700609 public static final int TYPE_MOBILE_IA = 14;
repo syncaea743a2011-07-29 23:55:49 -0700610
Lorenzo Colittie285b432015-04-23 15:32:42 +0900611 /**
Robert Greenwalt4bd43892015-07-09 14:49:35 -0700612 * Emergency PDN connection for emergency services. This
613 * may include IMS and MMS in emergency situations.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900614 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_EIMS} instead.
Ram3e0e3bc2014-06-26 11:03:44 -0700615 * {@hide}
616 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900617 @Deprecated
Ram3e0e3bc2014-06-26 11:03:44 -0700618 public static final int TYPE_MOBILE_EMERGENCY = 15;
619
Hui Lu1c5624a2014-01-15 11:05:36 -0500620 /**
621 * The network that uses proxy to achieve connectivity.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900622 * @deprecated Use {@link NetworkCapabilities} instead.
Hui Lu1c5624a2014-01-15 11:05:36 -0500623 * {@hide}
624 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900625 @Deprecated
Hui Lu1c5624a2014-01-15 11:05:36 -0500626 public static final int TYPE_PROXY = 16;
Wink Saville5e56bc52013-07-29 15:00:57 -0700627
Robert Greenwalt8283f882014-07-07 17:09:01 -0700628 /**
629 * A virtual network using one or more native bearers.
630 * It may or may not be providing security services.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900631 * @deprecated Applications should use {@link NetworkCapabilities#TRANSPORT_VPN} instead.
Robert Greenwalt8283f882014-07-07 17:09:01 -0700632 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900633 @Deprecated
Robert Greenwalt8283f882014-07-07 17:09:01 -0700634 public static final int TYPE_VPN = 17;
Hui Lu1c5624a2014-01-15 11:05:36 -0500635
636 /** {@hide} */
Robert Greenwalt8283f882014-07-07 17:09:01 -0700637 public static final int MAX_RADIO_TYPE = TYPE_VPN;
638
639 /** {@hide} */
640 public static final int MAX_NETWORK_TYPE = TYPE_VPN;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800641
Hugo Benichi16f0a942017-06-20 14:07:59 +0900642 private static final int MIN_NETWORK_TYPE = TYPE_MOBILE;
643
Jianzheng Zhoudcf03f32012-11-16 13:45:20 +0800644 /**
645 * If you want to set the default network preference,you can directly
646 * change the networkAttributes array in framework's config.xml.
647 *
648 * @deprecated Since we support so many more networks now, the single
649 * network default network preference can't really express
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800650 * the hierarchy. Instead, the default is defined by the
Jianzheng Zhoudcf03f32012-11-16 13:45:20 +0800651 * networkAttributes in config.xml. You can determine
Robert Greenwalt4c8b7482012-12-07 09:56:50 -0800652 * the current value by calling {@link #getNetworkPreference()}
Jianzheng Zhoudcf03f32012-11-16 13:45:20 +0800653 * from an App.
654 */
655 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800656 public static final int DEFAULT_NETWORK_PREFERENCE = TYPE_WIFI;
657
Jeff Sharkey625239a2012-09-26 22:03:49 -0700658 /**
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700659 * @hide
660 */
Hugo Benichia5c1f7f2017-06-20 14:10:14 +0900661 public static final int REQUEST_ID_UNSET = 0;
Robert Greenwalt7569f182014-06-08 16:42:59 -0700662
Paul Jensen5d59e782014-07-11 12:28:19 -0400663 /**
Hugo Benichi31c176d2017-06-17 13:14:12 +0900664 * Static unique request used as a tombstone for NetworkCallbacks that have been unregistered.
665 * This allows to distinguish when unregistering NetworkCallbacks those that were never
666 * registered and those that were already unregistered.
667 * @hide
668 */
Hugo Benichia5c1f7f2017-06-20 14:10:14 +0900669 private static final NetworkRequest ALREADY_UNREGISTERED =
Hugo Benichi31c176d2017-06-17 13:14:12 +0900670 new NetworkRequest.Builder().clearCapabilities().build();
671
672 /**
Paul Jensen5d59e782014-07-11 12:28:19 -0400673 * A NetID indicating no Network is selected.
674 * Keep in sync with bionic/libc/dns/include/resolv_netid.h
675 * @hide
676 */
677 public static final int NETID_UNSET = 0;
678
Erik Kline4d092232017-10-30 15:29:44 +0900679 /**
680 * Private DNS Mode values.
681 *
682 * The "private_dns_mode" global setting stores a String value which is
683 * expected to be one of the following.
684 */
685
686 /**
687 * @hide
688 */
689 public static final String PRIVATE_DNS_MODE_OFF = "off";
690 /**
691 * @hide
692 */
693 public static final String PRIVATE_DNS_MODE_OPPORTUNISTIC = "opportunistic";
694 /**
695 * @hide
696 */
697 public static final String PRIVATE_DNS_MODE_PROVIDER_HOSTNAME = "hostname";
698 /**
699 * The default Private DNS mode.
700 *
701 * This may change from release to release or may become dependent upon
702 * the capabilities of the underlying platform.
703 *
704 * @hide
705 */
706 public static final String PRIVATE_DNS_DEFAULT_MODE = PRIVATE_DNS_MODE_OPPORTUNISTIC;
707
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700708 private final IConnectivityManager mService;
Paul Jensene0bef712014-12-10 15:12:18 -0500709 /**
710 * A kludge to facilitate static access where a Context pointer isn't available, like in the
711 * case of the static set/getProcessDefaultNetwork methods and from the Network class.
712 * TODO: Remove this after deprecating the static methods in favor of non-static methods or
713 * methods that take a Context argument.
714 */
715 private static ConnectivityManager sInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800716
Lorenzo Colittiffc42b02015-07-29 11:41:21 +0900717 private final Context mContext;
718
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800719 private INetworkManagementService mNMService;
Felipe Leme1b103232016-01-22 09:44:57 -0800720 private INetworkPolicyManager mNPManager;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800721
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800722 /**
723 * Tests if a given integer represents a valid network type.
724 * @param networkType the type to be tested
725 * @return a boolean. {@code true} if the type is valid, else {@code false}
Paul Jensen9e59e122015-05-06 10:42:25 -0400726 * @deprecated All APIs accepting a network type are deprecated. There should be no need to
727 * validate a network type.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800728 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700729 @Deprecated
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700730 public static boolean isNetworkTypeValid(int networkType) {
Hugo Benichi16f0a942017-06-20 14:07:59 +0900731 return MIN_NETWORK_TYPE <= networkType && networkType <= MAX_NETWORK_TYPE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800732 }
733
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800734 /**
735 * Returns a non-localized string representing a given network type.
736 * ONLY used for debugging output.
737 * @param type the type needing naming
738 * @return a String for the given type, or a string version of the type ("87")
739 * if no name is known.
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900740 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800741 * {@hide}
742 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900743 @Deprecated
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700744 public static String getNetworkTypeName(int type) {
745 switch (type) {
Hugo Benichi16f0a942017-06-20 14:07:59 +0900746 case TYPE_NONE:
747 return "NONE";
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700748 case TYPE_MOBILE:
749 return "MOBILE";
750 case TYPE_WIFI:
751 return "WIFI";
752 case TYPE_MOBILE_MMS:
753 return "MOBILE_MMS";
754 case TYPE_MOBILE_SUPL:
755 return "MOBILE_SUPL";
756 case TYPE_MOBILE_DUN:
757 return "MOBILE_DUN";
758 case TYPE_MOBILE_HIPRI:
759 return "MOBILE_HIPRI";
760 case TYPE_WIMAX:
761 return "WIMAX";
762 case TYPE_BLUETOOTH:
763 return "BLUETOOTH";
764 case TYPE_DUMMY:
765 return "DUMMY";
766 case TYPE_ETHERNET:
767 return "ETHERNET";
768 case TYPE_MOBILE_FOTA:
769 return "MOBILE_FOTA";
770 case TYPE_MOBILE_IMS:
771 return "MOBILE_IMS";
772 case TYPE_MOBILE_CBS:
773 return "MOBILE_CBS";
repo syncaea743a2011-07-29 23:55:49 -0700774 case TYPE_WIFI_P2P:
775 return "WIFI_P2P";
Wink Saville5e56bc52013-07-29 15:00:57 -0700776 case TYPE_MOBILE_IA:
777 return "MOBILE_IA";
Ram3e0e3bc2014-06-26 11:03:44 -0700778 case TYPE_MOBILE_EMERGENCY:
779 return "MOBILE_EMERGENCY";
Hui Lu1c5624a2014-01-15 11:05:36 -0500780 case TYPE_PROXY:
781 return "PROXY";
Erik Kline37fbfa12014-11-19 17:23:41 +0900782 case TYPE_VPN:
783 return "VPN";
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700784 default:
785 return Integer.toString(type);
786 }
787 }
788
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800789 /**
790 * Checks if a given type uses the cellular data connection.
791 * This should be replaced in the future by a network property.
792 * @param networkType the type to check
793 * @return a boolean - {@code true} if uses cellular network, else {@code false}
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900794 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800795 * {@hide}
796 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900797 @Deprecated
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700798 public static boolean isNetworkTypeMobile(int networkType) {
799 switch (networkType) {
800 case TYPE_MOBILE:
801 case TYPE_MOBILE_MMS:
802 case TYPE_MOBILE_SUPL:
803 case TYPE_MOBILE_DUN:
804 case TYPE_MOBILE_HIPRI:
805 case TYPE_MOBILE_FOTA:
806 case TYPE_MOBILE_IMS:
807 case TYPE_MOBILE_CBS:
Wink Saville5e56bc52013-07-29 15:00:57 -0700808 case TYPE_MOBILE_IA:
Ram3e0e3bc2014-06-26 11:03:44 -0700809 case TYPE_MOBILE_EMERGENCY:
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700810 return true;
811 default:
812 return false;
813 }
814 }
815
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800816 /**
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700817 * Checks if the given network type is backed by a Wi-Fi radio.
818 *
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900819 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700820 * @hide
821 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +0900822 @Deprecated
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700823 public static boolean isNetworkTypeWifi(int networkType) {
824 switch (networkType) {
825 case TYPE_WIFI:
826 case TYPE_WIFI_P2P:
827 return true;
828 default:
829 return false;
830 }
831 }
832
833 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800834 * Specifies the preferred network type. When the device has more
835 * than one type available the preferred network type will be used.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800836 *
837 * @param preference the network type to prefer over all others. It is
838 * unspecified what happens to the old preferred network in the
839 * overall ordering.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -0700840 * @deprecated Functionality has been removed as it no longer makes sense,
841 * with many more than two networks - we'd need an array to express
842 * preference. Instead we use dynamic network properties of
843 * the networks to describe their precedence.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800844 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700845 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800846 public void setNetworkPreference(int preference) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800847 }
848
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800849 /**
850 * Retrieves the current preferred network type.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800851 *
852 * @return an integer representing the preferred network type
853 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -0700854 * @deprecated Functionality has been removed as it no longer makes sense,
855 * with many more than two networks - we'd need an array to express
856 * preference. Instead we use dynamic network properties of
857 * the networks to describe their precedence.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800858 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700859 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -0600860 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800861 public int getNetworkPreference() {
Robert Greenwaltd19c41c2014-05-18 23:07:25 -0700862 return TYPE_NONE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800863 }
864
Scott Main671644c2011-10-06 19:02:28 -0700865 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800866 * Returns details about the currently active default data network. When
867 * connected, this network is the default route for outgoing connections.
868 * You should always check {@link NetworkInfo#isConnected()} before initiating
869 * network traffic. This may return {@code null} when there is no default
870 * network.
Chalard Jean5a041d12018-03-29 17:45:24 +0900871 * Note that if the default network is a VPN, this method will return the
872 * NetworkInfo for one of its underlying networks instead, or null if the
873 * VPN agent did not specify any. Apps interested in learning about VPNs
874 * should use {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800875 *
876 * @return a {@link NetworkInfo} object for the current default network
Paul Jensen0d719ca2015-02-13 14:18:39 -0500877 * or {@code null} if no default network is currently active
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -0700878 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -0600879 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800880 public NetworkInfo getActiveNetworkInfo() {
881 try {
882 return mService.getActiveNetworkInfo();
883 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -0700884 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800885 }
886 }
887
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800888 /**
Paul Jensen31a94f42015-02-13 14:18:39 -0500889 * Returns a {@link Network} object corresponding to the currently active
890 * default data network. In the event that the current active default data
891 * network disconnects, the returned {@code Network} object will no longer
892 * be usable. This will return {@code null} when there is no default
893 * network.
894 *
895 * @return a {@link Network} object for the current default network or
896 * {@code null} if no default network is currently active
Paul Jensen31a94f42015-02-13 14:18:39 -0500897 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -0600898 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Paul Jensen31a94f42015-02-13 14:18:39 -0500899 public Network getActiveNetwork() {
900 try {
901 return mService.getActiveNetwork();
902 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -0700903 throw e.rethrowFromSystemServer();
Paul Jensen31a94f42015-02-13 14:18:39 -0500904 }
905 }
906
907 /**
Robin Leed2baf792016-03-24 12:07:00 +0000908 * Returns a {@link Network} object corresponding to the currently active
909 * default data network for a specific UID. In the event that the default data
910 * network disconnects, the returned {@code Network} object will no longer
911 * be usable. This will return {@code null} when there is no default
912 * network for the UID.
Robin Leed2baf792016-03-24 12:07:00 +0000913 *
914 * @return a {@link Network} object for the current default network for the
915 * given UID or {@code null} if no default network is currently active
916 *
917 * @hide
918 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -0600919 @RequiresPermission(android.Manifest.permission.CONNECTIVITY_INTERNAL)
Robin Leed2baf792016-03-24 12:07:00 +0000920 public Network getActiveNetworkForUid(int uid) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600921 return getActiveNetworkForUid(uid, false);
922 }
923
924 /** {@hide} */
925 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +0000926 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600927 return mService.getActiveNetworkForUid(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +0000928 } catch (RemoteException e) {
929 throw e.rethrowFromSystemServer();
930 }
931 }
932
933 /**
Charles He36738632017-05-15 17:07:18 +0100934 * Checks if a VPN app supports always-on mode.
935 *
936 * In order to support the always-on feature, an app has to
937 * <ul>
938 * <li>target {@link VERSION_CODES#N API 24} or above, and
Charles Hec57a01c2017-08-15 15:30:22 +0100939 * <li>not opt out through the {@link VpnService#SERVICE_META_DATA_SUPPORTS_ALWAYS_ON}
940 * meta-data field.
Charles He36738632017-05-15 17:07:18 +0100941 * </ul>
942 *
943 * @param userId The identifier of the user for whom the VPN app is installed.
944 * @param vpnPackage The canonical package name of the VPN app.
945 * @return {@code true} if and only if the VPN app exists and supports always-on mode.
946 * @hide
947 */
948 public boolean isAlwaysOnVpnPackageSupportedForUser(int userId, @Nullable String vpnPackage) {
949 try {
950 return mService.isAlwaysOnVpnPackageSupported(userId, vpnPackage);
951 } catch (RemoteException e) {
952 throw e.rethrowFromSystemServer();
953 }
954 }
955
956 /**
Robin Lee244ce8e2016-01-05 18:03:46 +0000957 * Configures an always-on VPN connection through a specific application.
958 * This connection is automatically granted and persisted after a reboot.
959 *
960 * <p>The designated package should declare a {@link VpnService} in its
961 * manifest guarded by {@link android.Manifest.permission.BIND_VPN_SERVICE},
962 * otherwise the call will fail.
963 *
964 * @param userId The identifier of the user to set an always-on VPN for.
965 * @param vpnPackage The package name for an installed VPN app on the device, or {@code null}
966 * to remove an existing always-on VPN configuration.
Robin Leedc679712016-05-03 13:23:03 +0100967 * @param lockdownEnabled {@code true} to disallow networking when the VPN is not connected or
968 * {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +0000969 * @return {@code true} if the package is set as always-on VPN controller;
970 * {@code false} otherwise.
971 * @hide
972 */
Robin Leedc679712016-05-03 13:23:03 +0100973 public boolean setAlwaysOnVpnPackageForUser(int userId, @Nullable String vpnPackage,
974 boolean lockdownEnabled) {
Robin Lee244ce8e2016-01-05 18:03:46 +0000975 try {
Robin Leedc679712016-05-03 13:23:03 +0100976 return mService.setAlwaysOnVpnPackage(userId, vpnPackage, lockdownEnabled);
Robin Lee244ce8e2016-01-05 18:03:46 +0000977 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -0700978 throw e.rethrowFromSystemServer();
Robin Lee244ce8e2016-01-05 18:03:46 +0000979 }
980 }
981
982 /**
983 * Returns the package name of the currently set always-on VPN application.
984 * If there is no always-on VPN set, or the VPN is provided by the system instead
985 * of by an app, {@code null} will be returned.
986 *
987 * @return Package name of VPN controller responsible for always-on VPN,
988 * or {@code null} if none is set.
989 * @hide
990 */
991 public String getAlwaysOnVpnPackageForUser(int userId) {
992 try {
993 return mService.getAlwaysOnVpnPackage(userId);
994 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -0700995 throw e.rethrowFromSystemServer();
Robin Lee244ce8e2016-01-05 18:03:46 +0000996 }
997 }
998
999 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001000 * Returns details about the currently active default data network
1001 * for a given uid. This is for internal use only to avoid spying
1002 * other apps.
1003 *
1004 * @return a {@link NetworkInfo} object for the current default network
1005 * for the given uid or {@code null} if no default network is
1006 * available for the specified uid.
1007 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001008 * {@hide}
1009 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001010 @RequiresPermission(android.Manifest.permission.CONNECTIVITY_INTERNAL)
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001011 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001012 return getActiveNetworkInfoForUid(uid, false);
1013 }
1014
1015 /** {@hide} */
1016 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001017 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001018 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001019 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001020 throw e.rethrowFromSystemServer();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001021 }
1022 }
1023
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001024 /**
1025 * Returns connection status information about a particular
1026 * network type.
1027 *
1028 * @param networkType integer specifying which networkType in
1029 * which you're interested.
1030 * @return a {@link NetworkInfo} object for the requested
1031 * network type or {@code null} if the type is not
Chalard Jean5a041d12018-03-29 17:45:24 +09001032 * supported by the device. If {@code networkType} is
1033 * TYPE_VPN and a VPN is active for the calling app,
1034 * then this method will try to return one of the
1035 * underlying networks for the VPN or null if the
1036 * VPN agent didn't specify any.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001037 *
Paul Jensen3541e9f2015-03-18 12:23:02 -04001038 * @deprecated This method does not support multiple connected networks
1039 * of the same type. Use {@link #getAllNetworks} and
1040 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001041 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001042 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001043 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001044 public NetworkInfo getNetworkInfo(int networkType) {
1045 try {
1046 return mService.getNetworkInfo(networkType);
1047 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001048 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001049 }
1050 }
1051
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001052 /**
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001053 * Returns connection status information about a particular
1054 * Network.
1055 *
1056 * @param network {@link Network} specifying which network
1057 * in which you're interested.
1058 * @return a {@link NetworkInfo} object for the requested
1059 * network or {@code null} if the {@code Network}
1060 * is not valid.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001061 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001062 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001063 public NetworkInfo getNetworkInfo(Network network) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001064 return getNetworkInfoForUid(network, Process.myUid(), false);
1065 }
1066
1067 /** {@hide} */
1068 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001069 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001070 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001071 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001072 throw e.rethrowFromSystemServer();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001073 }
1074 }
1075
1076 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001077 * Returns connection status information about all network
1078 * types supported by the device.
1079 *
1080 * @return an array of {@link NetworkInfo} objects. Check each
1081 * {@link NetworkInfo#getType} for which type each applies.
1082 *
Paul Jensen3541e9f2015-03-18 12:23:02 -04001083 * @deprecated This method does not support multiple connected networks
1084 * of the same type. Use {@link #getAllNetworks} and
1085 * {@link #getNetworkInfo(android.net.Network)} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001086 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001087 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001088 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001089 public NetworkInfo[] getAllNetworkInfo() {
1090 try {
1091 return mService.getAllNetworkInfo();
1092 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001093 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001094 }
1095 }
1096
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001097 /**
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001098 * Returns the {@link Network} object currently serving a given type, or
1099 * null if the given type is not connected.
1100 *
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001101 * @hide
Paul Jensen3541e9f2015-03-18 12:23:02 -04001102 * @deprecated This method does not support multiple connected networks
1103 * of the same type. Use {@link #getAllNetworks} and
1104 * {@link #getNetworkInfo(android.net.Network)} instead.
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001105 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001106 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001107 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001108 public Network getNetworkForType(int networkType) {
1109 try {
1110 return mService.getNetworkForType(networkType);
1111 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001112 throw e.rethrowFromSystemServer();
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001113 }
1114 }
1115
1116 /**
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001117 * Returns an array of all {@link Network} currently tracked by the
1118 * framework.
Paul Jensenb2748922015-05-06 11:10:18 -04001119 *
1120 * @return an array of {@link Network} objects.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001121 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001122 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001123 public Network[] getAllNetworks() {
1124 try {
1125 return mService.getAllNetworks();
1126 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001127 throw e.rethrowFromSystemServer();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001128 }
1129 }
1130
1131 /**
Lorenzo Colittie285b432015-04-23 15:32:42 +09001132 * Returns an array of {@link android.net.NetworkCapabilities} objects, representing
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001133 * the Networks that applications run by the given user will use by default.
1134 * @hide
1135 */
1136 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1137 try {
1138 return mService.getDefaultNetworkCapabilitiesForUser(userId);
1139 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001140 throw e.rethrowFromSystemServer();
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001141 }
1142 }
1143
1144 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001145 * Returns the IP information for the current default network.
1146 *
1147 * @return a {@link LinkProperties} object describing the IP info
1148 * for the current default network, or {@code null} if there
1149 * is no current default network.
1150 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001151 * {@hide}
1152 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001153 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001154 public LinkProperties getActiveLinkProperties() {
1155 try {
1156 return mService.getActiveLinkProperties();
1157 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001158 throw e.rethrowFromSystemServer();
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001159 }
1160 }
1161
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001162 /**
1163 * Returns the IP information for a given network type.
1164 *
1165 * @param networkType the network type of interest.
1166 * @return a {@link LinkProperties} object describing the IP info
1167 * for the given networkType, or {@code null} if there is
1168 * no current default network.
1169 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001170 * {@hide}
Paul Jensen3541e9f2015-03-18 12:23:02 -04001171 * @deprecated This method does not support multiple connected networks
1172 * of the same type. Use {@link #getAllNetworks},
1173 * {@link #getNetworkInfo(android.net.Network)}, and
1174 * {@link #getLinkProperties(android.net.Network)} instead.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001175 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001176 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001177 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001178 public LinkProperties getLinkProperties(int networkType) {
1179 try {
Robert Greenwalt9258c642014-03-26 16:47:06 -07001180 return mService.getLinkPropertiesForType(networkType);
1181 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001182 throw e.rethrowFromSystemServer();
Robert Greenwalt9258c642014-03-26 16:47:06 -07001183 }
1184 }
1185
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001186 /**
1187 * Get the {@link LinkProperties} for the given {@link Network}. This
1188 * will return {@code null} if the network is unknown.
1189 *
1190 * @param network The {@link Network} object identifying the network in question.
1191 * @return The {@link LinkProperties} for the network, or {@code null}.
Paul Jensenb2748922015-05-06 11:10:18 -04001192 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001193 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Robert Greenwalt9258c642014-03-26 16:47:06 -07001194 public LinkProperties getLinkProperties(Network network) {
1195 try {
1196 return mService.getLinkProperties(network);
1197 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001198 throw e.rethrowFromSystemServer();
Robert Greenwalt9258c642014-03-26 16:47:06 -07001199 }
1200 }
1201
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001202 /**
Lorenzo Colittie285b432015-04-23 15:32:42 +09001203 * Get the {@link android.net.NetworkCapabilities} for the given {@link Network}. This
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001204 * will return {@code null} if the network is unknown.
1205 *
1206 * @param network The {@link Network} object identifying the network in question.
Lorenzo Colittie285b432015-04-23 15:32:42 +09001207 * @return The {@link android.net.NetworkCapabilities} for the network, or {@code null}.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001208 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06001209 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Robert Greenwalt9258c642014-03-26 16:47:06 -07001210 public NetworkCapabilities getNetworkCapabilities(Network network) {
1211 try {
1212 return mService.getNetworkCapabilities(network);
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001213 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001214 throw e.rethrowFromSystemServer();
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001215 }
1216 }
1217
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001218 /**
Udam Sainib7c24872016-01-04 12:16:14 -08001219 * Gets the URL that should be used for resolving whether a captive portal is present.
1220 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1221 * portal is present.
1222 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1223 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1224 *
1225 * @hide
1226 */
1227 @SystemApi
Udam Saini0e94c362017-06-07 12:06:28 -07001228 @RequiresPermission(android.Manifest.permission.LOCAL_MAC_ADDRESS)
Udam Sainib7c24872016-01-04 12:16:14 -08001229 public String getCaptivePortalServerUrl() {
1230 try {
1231 return mService.getCaptivePortalServerUrl();
1232 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001233 throw e.rethrowFromSystemServer();
Udam Sainib7c24872016-01-04 12:16:14 -08001234 }
1235 }
1236
1237 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001238 * Tells the underlying networking system that the caller wants to
1239 * begin using the named feature. The interpretation of {@code feature}
1240 * is completely up to each networking implementation.
Lorenzo Colittid5427052015-10-15 16:29:00 +09001241 *
1242 * <p>This method requires the caller to hold either the
1243 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1244 * or the ability to modify system settings as determined by
1245 * {@link android.provider.Settings.System#canWrite}.</p>
1246 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001247 * @param networkType specifies which network the request pertains to
1248 * @param feature the name of the feature to be used
1249 * @return an integer value representing the outcome of the request.
1250 * The interpretation of this value is specific to each networking
1251 * implementation+feature combination, except that the value {@code -1}
1252 * always indicates failure.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001253 *
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +09001254 * @deprecated Deprecated in favor of the cleaner
1255 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
Dianne Hackborn692a2442015-07-31 10:35:34 -07001256 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001257 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti2187df72016-12-09 18:39:30 +09001258 * @removed
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001259 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001260 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001261 public int startUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001262 checkLegacyRoutingApiAccess();
Robert Greenwalt562cc542014-05-15 18:07:26 -07001263 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1264 if (netCap == null) {
1265 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1266 feature);
1267 return PhoneConstants.APN_REQUEST_FAILED;
1268 }
1269
1270 NetworkRequest request = null;
1271 synchronized (sLegacyRequests) {
1272 LegacyRequest l = sLegacyRequests.get(netCap);
1273 if (l != null) {
1274 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1275 renewRequestLocked(l);
1276 if (l.currentNetwork != null) {
1277 return PhoneConstants.APN_ALREADY_ACTIVE;
1278 } else {
1279 return PhoneConstants.APN_REQUEST_STARTED;
1280 }
1281 }
1282
1283 request = requestNetworkForFeatureLocked(netCap);
1284 }
1285 if (request != null) {
Robert Greenwalt257ee5f2014-06-20 10:58:45 -07001286 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001287 return PhoneConstants.APN_REQUEST_STARTED;
1288 } else {
1289 Log.d(TAG, " request Failed");
1290 return PhoneConstants.APN_REQUEST_FAILED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001291 }
1292 }
1293
1294 /**
1295 * Tells the underlying networking system that the caller is finished
1296 * using the named feature. The interpretation of {@code feature}
1297 * is completely up to each networking implementation.
Lorenzo Colittid5427052015-10-15 16:29:00 +09001298 *
1299 * <p>This method requires the caller to hold either the
1300 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1301 * or the ability to modify system settings as determined by
1302 * {@link android.provider.Settings.System#canWrite}.</p>
1303 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001304 * @param networkType specifies which network the request pertains to
1305 * @param feature the name of the feature that is no longer needed
1306 * @return an integer value representing the outcome of the request.
1307 * The interpretation of this value is specific to each networking
1308 * implementation+feature combination, except that the value {@code -1}
1309 * always indicates failure.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001310 *
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09001311 * @deprecated Deprecated in favor of the cleaner
1312 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
Dianne Hackborn692a2442015-07-31 10:35:34 -07001313 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001314 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti2187df72016-12-09 18:39:30 +09001315 * @removed
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001316 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001317 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001318 public int stopUsingNetworkFeature(int networkType, String feature) {
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001319 checkLegacyRoutingApiAccess();
Robert Greenwalt562cc542014-05-15 18:07:26 -07001320 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1321 if (netCap == null) {
1322 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
1323 feature);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001324 return -1;
1325 }
Robert Greenwalt562cc542014-05-15 18:07:26 -07001326
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001327 if (removeRequestForFeature(netCap)) {
Robert Greenwalt562cc542014-05-15 18:07:26 -07001328 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001329 }
1330 return 1;
1331 }
1332
1333 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
1334 if (networkType == TYPE_MOBILE) {
Erik Kline35bf06c2017-01-26 18:08:28 +09001335 switch (feature) {
1336 case "enableCBS":
1337 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
1338 case "enableDUN":
1339 case "enableDUNAlways":
1340 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
1341 case "enableFOTA":
1342 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
1343 case "enableHIPRI":
1344 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
1345 case "enableIMS":
1346 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
1347 case "enableMMS":
1348 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
1349 case "enableSUPL":
1350 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
1351 default:
1352 return null;
Robert Greenwalt562cc542014-05-15 18:07:26 -07001353 }
Erik Kline35bf06c2017-01-26 18:08:28 +09001354 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
1355 return networkCapabilitiesForType(TYPE_WIFI_P2P);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001356 }
1357 return null;
1358 }
1359
Robert Greenwalt06314e42014-10-29 14:04:06 -07001360 /**
1361 * Guess what the network request was trying to say so that the resulting
1362 * network is accessible via the legacy (deprecated) API such as
1363 * requestRouteToHost.
Lorenzo Colittidef4cb02015-11-25 20:28:50 +09001364 *
1365 * This means we should try to be fairly precise about transport and
Robert Greenwalt06314e42014-10-29 14:04:06 -07001366 * capability but ignore things such as networkSpecifier.
1367 * If the request has more than one transport or capability it doesn't
1368 * match the old legacy requests (they selected only single transport/capability)
1369 * so this function cannot map the request to a single legacy type and
1370 * the resulting network will not be available to the legacy APIs.
1371 *
Lorenzo Colittidef4cb02015-11-25 20:28:50 +09001372 * This code is only called from the requestNetwork API (L and above).
1373 *
1374 * Setting a legacy type causes CONNECTIVITY_ACTION broadcasts, which are expensive
1375 * because they wake up lots of apps - see http://b/23350688 . So we currently only
1376 * do this for SUPL requests, which are the only ones that we know need it. If
1377 * omitting these broadcasts causes unacceptable app breakage, then for backwards
1378 * compatibility we can send them:
1379 *
1380 * if (targetSdkVersion < Build.VERSION_CODES.M) && // legacy API unsupported >= M
1381 * targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP)) // requestNetwork not present < L
1382 *
Robert Greenwalt06314e42014-10-29 14:04:06 -07001383 * TODO - This should be removed when the legacy APIs are removed.
1384 */
Ye Wenb87875e2014-07-21 14:19:01 -07001385 private int inferLegacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
1386 if (netCap == null) {
1387 return TYPE_NONE;
1388 }
Robert Greenwalt06314e42014-10-29 14:04:06 -07001389
Ye Wenb87875e2014-07-21 14:19:01 -07001390 if (!netCap.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
1391 return TYPE_NONE;
1392 }
Robert Greenwalt06314e42014-10-29 14:04:06 -07001393
Lifu Tang30f95a72016-01-07 23:20:38 -08001394 // Do this only for SUPL, until GnssLocationProvider is fixed. http://b/25876485 .
Lorenzo Colittidef4cb02015-11-25 20:28:50 +09001395 if (!netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1396 // NOTE: if this causes app breakage, we should not just comment out this early return;
1397 // instead, we should make this early return conditional on the requesting app's target
1398 // SDK version, as described in the comment above.
1399 return TYPE_NONE;
1400 }
1401
Robert Greenwalt06314e42014-10-29 14:04:06 -07001402 String type = null;
1403 int result = TYPE_NONE;
1404
Ye Wenb87875e2014-07-21 14:19:01 -07001405 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
Robert Greenwalt06314e42014-10-29 14:04:06 -07001406 type = "enableCBS";
1407 result = TYPE_MOBILE_CBS;
1408 } else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1409 type = "enableIMS";
1410 result = TYPE_MOBILE_IMS;
1411 } else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1412 type = "enableFOTA";
1413 result = TYPE_MOBILE_FOTA;
1414 } else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1415 type = "enableDUN";
1416 result = TYPE_MOBILE_DUN;
1417 } else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
Lorenzo Colittidef4cb02015-11-25 20:28:50 +09001418 type = "enableSUPL";
Robert Greenwalt06314e42014-10-29 14:04:06 -07001419 result = TYPE_MOBILE_SUPL;
Robert Greenwalt74ab4fa2015-08-28 12:37:54 -07001420 // back out this hack for mms as they no longer need this and it's causing
1421 // device slowdowns - b/23350688 (note, supl still needs this)
1422 //} else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1423 // type = "enableMMS";
1424 // result = TYPE_MOBILE_MMS;
Robert Greenwalt06314e42014-10-29 14:04:06 -07001425 } else if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1426 type = "enableHIPRI";
1427 result = TYPE_MOBILE_HIPRI;
Ye Wenb87875e2014-07-21 14:19:01 -07001428 }
Robert Greenwalt06314e42014-10-29 14:04:06 -07001429 if (type != null) {
1430 NetworkCapabilities testCap = networkCapabilitiesForFeature(TYPE_MOBILE, type);
1431 if (testCap.equalsNetCapabilities(netCap) && testCap.equalsTransportTypes(netCap)) {
1432 return result;
Ye Wenb87875e2014-07-21 14:19:01 -07001433 }
1434 }
1435 return TYPE_NONE;
1436 }
1437
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07001438 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
Robert Greenwalt562cc542014-05-15 18:07:26 -07001439 if (netCap == null) return TYPE_NONE;
1440 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
1441 return TYPE_MOBILE_CBS;
1442 }
1443 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
1444 return TYPE_MOBILE_IMS;
1445 }
1446 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
1447 return TYPE_MOBILE_FOTA;
1448 }
1449 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
1450 return TYPE_MOBILE_DUN;
1451 }
1452 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
1453 return TYPE_MOBILE_SUPL;
1454 }
1455 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
1456 return TYPE_MOBILE_MMS;
1457 }
1458 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
1459 return TYPE_MOBILE_HIPRI;
1460 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07001461 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
1462 return TYPE_WIFI_P2P;
1463 }
Robert Greenwalt562cc542014-05-15 18:07:26 -07001464 return TYPE_NONE;
1465 }
1466
1467 private static class LegacyRequest {
1468 NetworkCapabilities networkCapabilities;
1469 NetworkRequest networkRequest;
1470 int expireSequenceNumber;
1471 Network currentNetwork;
1472 int delay = -1;
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001473
1474 private void clearDnsBinding() {
1475 if (currentNetwork != null) {
1476 currentNetwork = null;
1477 setProcessDefaultNetworkForHostResolution(null);
1478 }
1479 }
1480
Robert Greenwalt6078b502014-06-11 16:05:07 -07001481 NetworkCallback networkCallback = new NetworkCallback() {
Robert Greenwalt562cc542014-05-15 18:07:26 -07001482 @Override
Robert Greenwalt6078b502014-06-11 16:05:07 -07001483 public void onAvailable(Network network) {
Robert Greenwalt562cc542014-05-15 18:07:26 -07001484 currentNetwork = network;
1485 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04001486 setProcessDefaultNetworkForHostResolution(network);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001487 }
1488 @Override
Robert Greenwalt6078b502014-06-11 16:05:07 -07001489 public void onLost(Network network) {
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001490 if (network.equals(currentNetwork)) clearDnsBinding();
Robert Greenwalt562cc542014-05-15 18:07:26 -07001491 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
1492 }
1493 };
1494 }
1495
Robert Greenwaltfab501672014-07-23 11:44:01 -07001496 private static HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
Robert Greenwalt562cc542014-05-15 18:07:26 -07001497 new HashMap<NetworkCapabilities, LegacyRequest>();
1498
1499 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
1500 synchronized (sLegacyRequests) {
1501 LegacyRequest l = sLegacyRequests.get(netCap);
1502 if (l != null) return l.networkRequest;
1503 }
1504 return null;
1505 }
1506
1507 private void renewRequestLocked(LegacyRequest l) {
1508 l.expireSequenceNumber++;
1509 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
1510 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
1511 }
1512
1513 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
1514 int ourSeqNum = -1;
1515 synchronized (sLegacyRequests) {
1516 LegacyRequest l = sLegacyRequests.get(netCap);
1517 if (l == null) return;
1518 ourSeqNum = l.expireSequenceNumber;
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001519 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001520 }
1521 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
1522 }
1523
1524 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
1525 int delay = -1;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07001526 int type = legacyTypeForNetworkCapabilities(netCap);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001527 try {
1528 delay = mService.getRestoreDefaultNetworkDelay(type);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001529 } catch (RemoteException e) {
1530 throw e.rethrowFromSystemServer();
1531 }
Robert Greenwalt562cc542014-05-15 18:07:26 -07001532 LegacyRequest l = new LegacyRequest();
1533 l.networkCapabilities = netCap;
1534 l.delay = delay;
1535 l.expireSequenceNumber = 0;
Hugo Benichi2583ef02017-02-02 17:02:36 +09001536 l.networkRequest = sendRequestForNetwork(
1537 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
Robert Greenwalt562cc542014-05-15 18:07:26 -07001538 if (l.networkRequest == null) return null;
1539 sLegacyRequests.put(netCap, l);
1540 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
1541 return l.networkRequest;
1542 }
1543
1544 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
1545 if (delay >= 0) {
1546 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
Hugo Benichi2583ef02017-02-02 17:02:36 +09001547 CallbackHandler handler = getDefaultHandler();
Hugo Benichi6f260f32017-02-03 14:18:44 +09001548 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
1549 handler.sendMessageDelayed(msg, delay);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001550 }
1551 }
1552
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001553 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
1554 final LegacyRequest l;
Robert Greenwalt562cc542014-05-15 18:07:26 -07001555 synchronized (sLegacyRequests) {
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001556 l = sLegacyRequests.remove(netCap);
Robert Greenwalt562cc542014-05-15 18:07:26 -07001557 }
Paul Jensen9ffb53c2014-12-17 10:39:34 -05001558 if (l == null) return false;
1559 unregisterNetworkCallback(l.networkCallback);
1560 l.clearDnsBinding();
1561 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001562 }
1563
Erik Kline35bf06c2017-01-26 18:08:28 +09001564 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
1565 static {
1566 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
1567 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
1568 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
1569 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
1570 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
1571 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1572 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
1573 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
1574 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
1575 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
1576 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
1577 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
1578 }
1579
1580 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
1581 static {
1582 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
1583 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
1584 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
1585 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
1586 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
1587 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
1588 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
1589 }
1590
1591 /**
1592 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
1593 * instance suitable for registering a request or callback. Throws an
1594 * IllegalArgumentException if no mapping from the legacy type to
1595 * NetworkCapabilities is known.
1596 *
Chalard Jean6b1da6e2018-03-08 13:54:53 +09001597 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
1598 * to find the network instead.
Erik Kline35bf06c2017-01-26 18:08:28 +09001599 * @hide
1600 */
1601 public static NetworkCapabilities networkCapabilitiesForType(int type) {
1602 final NetworkCapabilities nc = new NetworkCapabilities();
1603
1604 // Map from type to transports.
1605 final int NOT_FOUND = -1;
1606 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
Hugo Benichie7678512017-05-09 15:19:01 +09001607 Preconditions.checkArgument(transport != NOT_FOUND, "unknown legacy type: " + type);
Erik Kline35bf06c2017-01-26 18:08:28 +09001608 nc.addTransportType(transport);
1609
1610 // Map from type to capabilities.
1611 nc.addCapability(sLegacyTypeToCapability.get(
1612 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
1613 nc.maybeMarkCapabilitiesRestricted();
1614 return nc;
1615 }
1616
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001617 /** @hide */
1618 public static class PacketKeepaliveCallback {
1619 /** The requested keepalive was successfully started. */
1620 public void onStarted() {}
1621 /** The keepalive was successfully stopped. */
1622 public void onStopped() {}
1623 /** An error occurred. */
1624 public void onError(int error) {}
1625 }
1626
1627 /**
1628 * Allows applications to request that the system periodically send specific packets on their
1629 * behalf, using hardware offload to save battery power.
1630 *
1631 * To request that the system send keepalives, call one of the methods that return a
1632 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
1633 * passing in a non-null callback. If the callback is successfully started, the callback's
1634 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
1635 * specifying one of the {@code ERROR_*} constants in this class.
1636 *
1637 * To stop an existing keepalive, call {@link stop}. The system will call {@code onStopped} if
1638 * the operation was successfull or {@code onError} if an error occurred.
1639 *
1640 * @hide
1641 */
1642 public class PacketKeepalive {
1643
1644 private static final String TAG = "PacketKeepalive";
1645
1646 /** @hide */
1647 public static final int SUCCESS = 0;
1648
1649 /** @hide */
1650 public static final int NO_KEEPALIVE = -1;
1651
1652 /** @hide */
1653 public static final int BINDER_DIED = -10;
1654
1655 /** The specified {@code Network} is not connected. */
1656 public static final int ERROR_INVALID_NETWORK = -20;
1657 /** The specified IP addresses are invalid. For example, the specified source IP address is
1658 * not configured on the specified {@code Network}. */
1659 public static final int ERROR_INVALID_IP_ADDRESS = -21;
1660 /** The requested port is invalid. */
1661 public static final int ERROR_INVALID_PORT = -22;
1662 /** The packet length is invalid (e.g., too long). */
1663 public static final int ERROR_INVALID_LENGTH = -23;
1664 /** The packet transmission interval is invalid (e.g., too short). */
1665 public static final int ERROR_INVALID_INTERVAL = -24;
1666
1667 /** The hardware does not support this request. */
1668 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
Lorenzo Colitti9d1284e2015-09-08 16:46:36 +09001669 /** The hardware returned an error. */
1670 public static final int ERROR_HARDWARE_ERROR = -31;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001671
Nathan Harold63dd8132018-02-14 13:09:45 -08001672 /** The NAT-T destination port for IPsec */
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001673 public static final int NATT_PORT = 4500;
1674
Nathan Harold63dd8132018-02-14 13:09:45 -08001675 /** The minimum interval in seconds between keepalive packet transmissions */
1676 public static final int MIN_INTERVAL = 10;
1677
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001678 private final Network mNetwork;
1679 private final PacketKeepaliveCallback mCallback;
1680 private final Looper mLooper;
1681 private final Messenger mMessenger;
1682
1683 private volatile Integer mSlot;
1684
1685 void stopLooper() {
1686 mLooper.quit();
1687 }
1688
1689 public void stop() {
1690 try {
1691 mService.stopKeepalive(mNetwork, mSlot);
1692 } catch (RemoteException e) {
1693 Log.e(TAG, "Error stopping packet keepalive: ", e);
1694 stopLooper();
1695 }
1696 }
1697
1698 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09001699 Preconditions.checkNotNull(network, "network cannot be null");
1700 Preconditions.checkNotNull(callback, "callback cannot be null");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001701 mNetwork = network;
1702 mCallback = callback;
1703 HandlerThread thread = new HandlerThread(TAG);
1704 thread.start();
1705 mLooper = thread.getLooper();
1706 mMessenger = new Messenger(new Handler(mLooper) {
1707 @Override
1708 public void handleMessage(Message message) {
1709 switch (message.what) {
1710 case NetworkAgent.EVENT_PACKET_KEEPALIVE:
1711 int error = message.arg2;
1712 try {
1713 if (error == SUCCESS) {
1714 if (mSlot == null) {
1715 mSlot = message.arg1;
1716 mCallback.onStarted();
1717 } else {
1718 mSlot = null;
1719 stopLooper();
1720 mCallback.onStopped();
1721 }
1722 } else {
1723 stopLooper();
1724 mCallback.onError(error);
1725 }
1726 } catch (Exception e) {
1727 Log.e(TAG, "Exception in keepalive callback(" + error + ")", e);
1728 }
1729 break;
1730 default:
1731 Log.e(TAG, "Unhandled message " + Integer.toHexString(message.what));
1732 break;
1733 }
1734 }
1735 });
1736 }
1737 }
1738
1739 /**
1740 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
1741 *
1742 * @hide
1743 */
1744 public PacketKeepalive startNattKeepalive(
1745 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
1746 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
1747 final PacketKeepalive k = new PacketKeepalive(network, callback);
1748 try {
1749 mService.startNattKeepalive(network, intervalSeconds, k.mMessenger, new Binder(),
1750 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
1751 } catch (RemoteException e) {
1752 Log.e(TAG, "Error starting packet keepalive: ", e);
1753 k.stopLooper();
1754 return null;
1755 }
1756 return k;
1757 }
1758
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001759 /**
1760 * Ensure that a network route exists to deliver traffic to the specified
1761 * host via the specified network interface. An attempt to add a route that
1762 * already exists is ignored, but treated as successful.
Lorenzo Colittid5427052015-10-15 16:29:00 +09001763 *
1764 * <p>This method requires the caller to hold either the
1765 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1766 * or the ability to modify system settings as determined by
1767 * {@link android.provider.Settings.System#canWrite}.</p>
1768 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001769 * @param networkType the type of the network over which traffic to the specified
1770 * host is to be routed
1771 * @param hostAddress the IP address of the host to which the route is desired
1772 * @return {@code true} on success, {@code false} on failure
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001773 *
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +09001774 * @deprecated Deprecated in favor of the
1775 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
1776 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
Dianne Hackborn692a2442015-07-31 10:35:34 -07001777 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001778 * throw {@code UnsupportedOperationException} if called.
Lorenzo Colitti2187df72016-12-09 18:39:30 +09001779 * @removed
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001780 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001781 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001782 public boolean requestRouteToHost(int networkType, int hostAddress) {
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001783 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001784 }
1785
1786 /**
1787 * Ensure that a network route exists to deliver traffic to the specified
1788 * host via the specified network interface. An attempt to add a route that
1789 * already exists is ignored, but treated as successful.
Lorenzo Colittid5427052015-10-15 16:29:00 +09001790 *
1791 * <p>This method requires the caller to hold either the
1792 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1793 * or the ability to modify system settings as determined by
1794 * {@link android.provider.Settings.System#canWrite}.</p>
1795 *
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001796 * @param networkType the type of the network over which traffic to the specified
1797 * host is to be routed
1798 * @param hostAddress the IP address of the host to which the route is desired
1799 * @return {@code true} on success, {@code false} on failure
1800 * @hide
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07001801 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +09001802 * {@link #bindProcessToNetwork} API.
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001803 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001804 @Deprecated
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001805 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001806 checkLegacyRoutingApiAccess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001807 try {
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001808 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001809 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001810 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001811 }
1812 }
1813
1814 /**
1815 * Returns the value of the setting for background data usage. If false,
1816 * applications should not use the network if the application is not in the
1817 * foreground. Developers should respect this setting, and check the value
1818 * of this before performing any background data operations.
1819 * <p>
1820 * All applications that have background services that use the network
1821 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001822 * <p>
Scott Main4cc53332011-10-06 18:32:43 -07001823 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001824 * background data depends on several combined factors, and this method will
1825 * always return {@code true}. Instead, when background data is unavailable,
1826 * {@link #getActiveNetworkInfo()} will now appear disconnected.
Danica Chang6fdd0c62010-08-11 14:54:43 -07001827 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001828 * @return Whether background data usage is allowed.
1829 */
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001830 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001831 public boolean getBackgroundDataSetting() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001832 // assume that background data is allowed; final authority is
1833 // NetworkInfo which may be blocked.
1834 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001835 }
1836
1837 /**
1838 * Sets the value of the setting for background data usage.
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001839 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001840 * @param allowBackgroundData Whether an application should use data while
1841 * it is in the background.
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001842 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001843 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
1844 * @see #getBackgroundDataSetting()
1845 * @hide
1846 */
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001847 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001848 public void setBackgroundDataSetting(boolean allowBackgroundData) {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001849 // ignored
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001850 }
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001851
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001852 /** {@hide} */
1853 @Deprecated
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001854 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1855 try {
1856 return mService.getActiveNetworkQuotaInfo();
1857 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001858 throw e.rethrowFromSystemServer();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001859 }
1860 }
1861
1862 /**
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001863 * @hide
Robert Greenwaltafa05c02014-05-21 20:04:36 -07001864 * @deprecated Talk to TelephonyManager directly
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001865 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07001866 @Deprecated
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001867 public boolean getMobileDataEnabled() {
Robert Greenwaltafa05c02014-05-21 20:04:36 -07001868 IBinder b = ServiceManager.getService(Context.TELEPHONY_SERVICE);
1869 if (b != null) {
1870 try {
1871 ITelephony it = ITelephony.Stub.asInterface(b);
Shishir Agrawal7ea3e8b2016-01-25 13:03:07 -08001872 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
Wink Saville36ffb042014-12-05 11:10:30 -08001873 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
Malcolm Chenb455e722017-11-28 15:57:14 -08001874 boolean retVal = it.isUserDataEnabled(subId);
Wink Saville36ffb042014-12-05 11:10:30 -08001875 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
1876 + " retVal=" + retVal);
1877 return retVal;
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001878 } catch (RemoteException e) {
1879 throw e.rethrowFromSystemServer();
1880 }
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001881 }
Wink Saville36ffb042014-12-05 11:10:30 -08001882 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
Robert Greenwaltafa05c02014-05-21 20:04:36 -07001883 return false;
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001884 }
1885
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001886 /**
Robert Greenwaltb2489872014-09-04 16:44:35 -07001887 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
Robert Greenwalt6078b502014-06-11 16:05:07 -07001888 * to find out when the system default network has gone in to a high power state.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001889 */
1890 public interface OnNetworkActiveListener {
1891 /**
1892 * Called on the main thread of the process to report that the current data network
1893 * has become active, and it is now a good time to perform any pending network
1894 * operations. Note that this listener only tells you when the network becomes
1895 * active; if at any other time you want to know whether it is active (and thus okay
1896 * to initiate network traffic), you can retrieve its instantaneous state with
Robert Greenwalt6078b502014-06-11 16:05:07 -07001897 * {@link ConnectivityManager#isDefaultNetworkActive}.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001898 */
1899 public void onNetworkActive();
1900 }
1901
1902 private INetworkManagementService getNetworkManagementService() {
1903 synchronized (this) {
1904 if (mNMService != null) {
1905 return mNMService;
1906 }
1907 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
1908 mNMService = INetworkManagementService.Stub.asInterface(b);
1909 return mNMService;
1910 }
1911 }
1912
1913 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
1914 mNetworkActivityListeners
1915 = new ArrayMap<OnNetworkActiveListener, INetworkActivityListener>();
1916
1917 /**
Robert Greenwalt6078b502014-06-11 16:05:07 -07001918 * Start listening to reports when the system's default data network is active, meaning it is
1919 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
1920 * to determine the current state of the system's default network after registering the
1921 * listener.
1922 * <p>
1923 * If the process default network has been set with
Paul Jensen72db88e2015-03-10 10:54:12 -04001924 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
Robert Greenwalt6078b502014-06-11 16:05:07 -07001925 * reflect the process's default, but the system default.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001926 *
1927 * @param l The listener to be told when the network is active.
1928 */
Robert Greenwaltb2489872014-09-04 16:44:35 -07001929 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001930 INetworkActivityListener rl = new INetworkActivityListener.Stub() {
1931 @Override
1932 public void onNetworkActive() throws RemoteException {
1933 l.onNetworkActive();
1934 }
1935 };
1936
1937 try {
1938 getNetworkManagementService().registerNetworkActivityListener(rl);
1939 mNetworkActivityListeners.put(l, rl);
1940 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001941 throw e.rethrowFromSystemServer();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001942 }
1943 }
1944
1945 /**
1946 * Remove network active listener previously registered with
Robert Greenwaltb2489872014-09-04 16:44:35 -07001947 * {@link #addDefaultNetworkActiveListener}.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001948 *
1949 * @param l Previously registered listener.
1950 */
Robert Greenwaltb2489872014-09-04 16:44:35 -07001951 public void removeDefaultNetworkActiveListener(OnNetworkActiveListener l) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001952 INetworkActivityListener rl = mNetworkActivityListeners.get(l);
Hugo Benichie7678512017-05-09 15:19:01 +09001953 Preconditions.checkArgument(rl != null, "Listener was not registered.");
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001954 try {
1955 getNetworkManagementService().unregisterNetworkActivityListener(rl);
1956 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001957 throw e.rethrowFromSystemServer();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001958 }
1959 }
1960
1961 /**
1962 * Return whether the data network is currently active. An active network means that
1963 * it is currently in a high power state for performing data transmission. On some
1964 * types of networks, it may be expensive to move and stay in such a state, so it is
1965 * more power efficient to batch network traffic together when the radio is already in
1966 * this state. This method tells you whether right now is currently a good time to
1967 * initiate network traffic, as the network is already active.
1968 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07001969 public boolean isDefaultNetworkActive() {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001970 try {
1971 return getNetworkManagementService().isNetworkActive();
1972 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001973 throw e.rethrowFromSystemServer();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001974 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001975 }
1976
1977 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001978 * {@hide}
1979 */
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09001980 public ConnectivityManager(Context context, IConnectivityManager service) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09001981 mContext = Preconditions.checkNotNull(context, "missing context");
1982 mService = Preconditions.checkNotNull(service, "missing IConnectivityManager");
Paul Jensene0bef712014-12-10 15:12:18 -05001983 sInstance = this;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001984 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001985
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001986 /** {@hide} */
1987 public static ConnectivityManager from(Context context) {
1988 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
1989 }
1990
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09001991 /* TODO: These permissions checks don't belong in client-side code. Move them to
1992 * services.jar, possibly in com.android.server.net. */
1993
1994 /** {@hide} */
Lorenzo Colittid5427052015-10-15 16:29:00 +09001995 public static final void enforceChangePermission(Context context) {
1996 int uid = Binder.getCallingUid();
1997 Settings.checkAndNoteChangeNetworkStateOperation(context, uid, Settings
1998 .getPackageNameForUid(context, uid), true /* throwException */);
1999 }
2000
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002001 /** {@hide} */
2002 public static final void enforceTetherChangePermission(Context context, String callingPkg) {
Hugo Benichie7678512017-05-09 15:19:01 +09002003 Preconditions.checkNotNull(context, "Context cannot be null");
2004 Preconditions.checkNotNull(callingPkg, "callingPkg cannot be null");
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002005
Robert Greenwaltedb47662014-09-16 17:54:19 -07002006 if (context.getResources().getStringArray(
2007 com.android.internal.R.array.config_mobile_hotspot_provision_app).length == 2) {
2008 // Have a provisioning app - must only let system apps (which check this app)
2009 // turn on tethering
2010 context.enforceCallingOrSelfPermission(
Jeremy Kleind42209d2015-12-28 15:11:58 -08002011 android.Manifest.permission.TETHER_PRIVILEGED, "ConnectivityService");
Robert Greenwaltedb47662014-09-16 17:54:19 -07002012 } else {
Billy Laua7238a32015-08-01 12:45:02 +01002013 int uid = Binder.getCallingUid();
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002014 // If callingPkg's uid is not same as Binder.getCallingUid(),
2015 // AppOpsService throws SecurityException.
2016 Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPkg,
2017 true /* throwException */);
Robert Greenwaltedb47662014-09-16 17:54:19 -07002018 }
2019 }
2020
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002021 /**
Paul Jensene0bef712014-12-10 15:12:18 -05002022 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2023 * situations where a Context pointer is unavailable.
2024 * @hide
2025 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002026 @Deprecated
Paul Jensen72db88e2015-03-10 10:54:12 -04002027 static ConnectivityManager getInstanceOrNull() {
2028 return sInstance;
2029 }
2030
2031 /**
2032 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2033 * situations where a Context pointer is unavailable.
2034 * @hide
2035 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002036 @Deprecated
Paul Jensen72db88e2015-03-10 10:54:12 -04002037 private static ConnectivityManager getInstance() {
2038 if (getInstanceOrNull() == null) {
Paul Jensene0bef712014-12-10 15:12:18 -05002039 throw new IllegalStateException("No ConnectivityManager yet constructed");
2040 }
Paul Jensen72db88e2015-03-10 10:54:12 -04002041 return getInstanceOrNull();
Paul Jensene0bef712014-12-10 15:12:18 -05002042 }
2043
2044 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002045 * Get the set of tetherable, available interfaces. This list is limited by
2046 * device configuration and current interface existence.
2047 *
2048 * @return an array of 0 or more Strings of tetherable interface names.
2049 *
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002050 * {@hide}
2051 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002052 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002053 public String[] getTetherableIfaces() {
2054 try {
2055 return mService.getTetherableIfaces();
2056 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002057 throw e.rethrowFromSystemServer();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002058 }
2059 }
2060
2061 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002062 * Get the set of tethered interfaces.
2063 *
2064 * @return an array of 0 or more String of currently tethered interface names.
2065 *
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002066 * {@hide}
2067 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002068 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002069 public String[] getTetheredIfaces() {
2070 try {
2071 return mService.getTetheredIfaces();
2072 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002073 throw e.rethrowFromSystemServer();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002074 }
2075 }
2076
2077 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002078 * Get the set of interface names which attempted to tether but
2079 * failed. Re-attempting to tether may cause them to reset to the Tethered
2080 * state. Alternatively, causing the interface to be destroyed and recreated
2081 * may cause them to reset to the available state.
2082 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2083 * information on the cause of the errors.
2084 *
2085 * @return an array of 0 or more String indicating the interface names
2086 * which failed to tether.
2087 *
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002088 * {@hide}
2089 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002090 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Robert Greenwalt5a735062010-03-02 17:25:02 -08002091 public String[] getTetheringErroredIfaces() {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002092 try {
Robert Greenwalt5a735062010-03-02 17:25:02 -08002093 return mService.getTetheringErroredIfaces();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002094 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002095 throw e.rethrowFromSystemServer();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002096 }
2097 }
2098
2099 /**
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002100 * Get the set of tethered dhcp ranges.
2101 *
2102 * @return an array of 0 or more {@code String} of tethered dhcp ranges.
2103 * {@hide}
2104 */
2105 public String[] getTetheredDhcpRanges() {
2106 try {
2107 return mService.getTetheredDhcpRanges();
2108 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002109 throw e.rethrowFromSystemServer();
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002110 }
2111 }
2112
2113 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002114 * Attempt to tether the named interface. This will setup a dhcp server
2115 * on the interface, forward and NAT IP packets and forward DNS requests
2116 * to the best active upstream network interface. Note that if no upstream
2117 * IP network interface is available, dhcp will still run and traffic will be
2118 * allowed between the tethered devices and this device, though upstream net
2119 * access will of course fail until an upstream network interface becomes
2120 * active.
Lorenzo Colittid5427052015-10-15 16:29:00 +09002121 *
2122 * <p>This method requires the caller to hold either the
2123 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2124 * or the ability to modify system settings as determined by
2125 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002126 *
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002127 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2128 * and WifiStateMachine which need direct access. All other clients should use
2129 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2130 * logic.</p>
2131 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002132 * @param iface the interface name to tether.
2133 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2134 *
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002135 * {@hide}
2136 */
Robert Greenwalt5a735062010-03-02 17:25:02 -08002137 public int tether(String iface) {
2138 try {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002139 String pkgName = mContext.getOpPackageName();
2140 Log.i(TAG, "tether caller:" + pkgName);
2141 return mService.tether(iface, pkgName);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002142 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002143 throw e.rethrowFromSystemServer();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002144 }
2145 }
2146
2147 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002148 * Stop tethering the named interface.
Lorenzo Colittid5427052015-10-15 16:29:00 +09002149 *
2150 * <p>This method requires the caller to hold either the
2151 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2152 * or the ability to modify system settings as determined by
2153 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002154 *
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002155 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2156 * and WifiStateMachine which need direct access. All other clients should use
2157 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2158 * logic.</p>
2159 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002160 * @param iface the interface name to untether.
2161 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2162 *
Robert Greenwalt5a735062010-03-02 17:25:02 -08002163 * {@hide}
2164 */
2165 public int untether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002166 try {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002167 String pkgName = mContext.getOpPackageName();
2168 Log.i(TAG, "untether caller:" + pkgName);
2169 return mService.untether(iface, pkgName);
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002170 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002171 throw e.rethrowFromSystemServer();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002172 }
2173 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002174
2175 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002176 * Check if the device allows for tethering. It may be disabled via
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002177 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002178 * due to device configuration.
2179 *
Chalard Jean8f76fc32017-09-26 15:45:18 +09002180 * <p>If this app does not have permission to use this API, it will always
2181 * return false rather than throw an exception.</p>
2182 *
2183 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2184 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2185 *
2186 * <p>Otherwise, this method requires the caller to hold the ability to modify system
2187 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
2188 *
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002189 * @return a boolean - {@code true} indicating Tethering is supported.
2190 *
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002191 * {@hide}
2192 */
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002193 @SystemApi
Chalard Jean8f76fc32017-09-26 15:45:18 +09002194 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2195 android.Manifest.permission.WRITE_SETTINGS})
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002196 public boolean isTetheringSupported() {
Chalard Jean8f76fc32017-09-26 15:45:18 +09002197 String pkgName = mContext.getOpPackageName();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002198 try {
Udam Saini0e94c362017-06-07 12:06:28 -07002199 return mService.isTetheringSupported(pkgName);
Chalard Jean8f76fc32017-09-26 15:45:18 +09002200 } catch (SecurityException e) {
2201 // This API is not available to this caller, but for backward-compatibility
2202 // this will just return false instead of throwing.
2203 return false;
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002204 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002205 throw e.rethrowFromSystemServer();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002206 }
2207 }
2208
2209 /**
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002210 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
2211 * @hide
2212 */
2213 @SystemApi
2214 public static abstract class OnStartTetheringCallback {
2215 /**
2216 * Called when tethering has been successfully started.
2217 */
2218 public void onTetheringStarted() {};
2219
2220 /**
2221 * Called when starting tethering failed.
2222 */
2223 public void onTetheringFailed() {};
2224 }
2225
2226 /**
2227 * Convenient overload for
2228 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
2229 * handler to run on the current thread's {@link Looper}.
2230 * @hide
2231 */
2232 @SystemApi
Udam Saini0e94c362017-06-07 12:06:28 -07002233 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002234 public void startTethering(int type, boolean showProvisioningUi,
2235 final OnStartTetheringCallback callback) {
2236 startTethering(type, showProvisioningUi, callback, null);
2237 }
2238
2239 /**
2240 * Runs tether provisioning for the given type if needed and then starts tethering if
2241 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
2242 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
2243 * schedules tether provisioning re-checks if appropriate.
2244 *
2245 * @param type The type of tethering to start. Must be one of
2246 * {@link ConnectivityManager.TETHERING_WIFI},
2247 * {@link ConnectivityManager.TETHERING_USB}, or
2248 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2249 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
2250 * is one. This should be true the first time this function is called and also any time
2251 * the user can see this UI. It gives users information from their carrier about the
2252 * check failing and how they can sign up for tethering if possible.
2253 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
2254 * of the result of trying to tether.
2255 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
2256 * @hide
2257 */
2258 @SystemApi
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -06002259 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002260 public void startTethering(int type, boolean showProvisioningUi,
2261 final OnStartTetheringCallback callback, Handler handler) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09002262 Preconditions.checkNotNull(callback, "OnStartTetheringCallback cannot be null.");
Jeremy Klein5f277e12016-03-12 16:29:54 -08002263
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002264 ResultReceiver wrappedCallback = new ResultReceiver(handler) {
2265 @Override
2266 protected void onReceiveResult(int resultCode, Bundle resultData) {
2267 if (resultCode == TETHER_ERROR_NO_ERROR) {
2268 callback.onTetheringStarted();
2269 } else {
2270 callback.onTetheringFailed();
2271 }
2272 }
2273 };
Jeremy Klein5f277e12016-03-12 16:29:54 -08002274
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002275 try {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002276 String pkgName = mContext.getOpPackageName();
2277 Log.i(TAG, "startTethering caller:" + pkgName);
2278 mService.startTethering(type, wrappedCallback, showProvisioningUi, pkgName);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002279 } catch (RemoteException e) {
2280 Log.e(TAG, "Exception trying to start tethering.", e);
2281 wrappedCallback.send(TETHER_ERROR_SERVICE_UNAVAIL, null);
2282 }
2283 }
2284
2285 /**
2286 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
2287 * applicable.
2288 *
2289 * @param type The type of tethering to stop. Must be one of
2290 * {@link ConnectivityManager.TETHERING_WIFI},
2291 * {@link ConnectivityManager.TETHERING_USB}, or
2292 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
2293 * @hide
2294 */
2295 @SystemApi
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -06002296 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002297 public void stopTethering(int type) {
2298 try {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002299 String pkgName = mContext.getOpPackageName();
2300 Log.i(TAG, "stopTethering caller:" + pkgName);
2301 mService.stopTethering(type, pkgName);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002302 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002303 throw e.rethrowFromSystemServer();
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002304 }
2305 }
2306
2307 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002308 * Get the list of regular expressions that define any tetherable
2309 * USB network interfaces. If USB tethering is not supported by the
2310 * device, this list should be empty.
2311 *
2312 * @return an array of 0 or more regular expression Strings defining
2313 * what interfaces are considered tetherable usb interfaces.
2314 *
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002315 * {@hide}
2316 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002317 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002318 public String[] getTetherableUsbRegexs() {
2319 try {
2320 return mService.getTetherableUsbRegexs();
2321 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002322 throw e.rethrowFromSystemServer();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002323 }
2324 }
2325
2326 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002327 * Get the list of regular expressions that define any tetherable
2328 * Wifi network interfaces. If Wifi tethering is not supported by the
2329 * device, this list should be empty.
2330 *
2331 * @return an array of 0 or more regular expression Strings defining
2332 * what interfaces are considered tetherable wifi interfaces.
2333 *
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002334 * {@hide}
2335 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002336 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002337 public String[] getTetherableWifiRegexs() {
2338 try {
2339 return mService.getTetherableWifiRegexs();
2340 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002341 throw e.rethrowFromSystemServer();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002342 }
2343 }
Robert Greenwalt5a735062010-03-02 17:25:02 -08002344
Danica Chang6fdd0c62010-08-11 14:54:43 -07002345 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002346 * Get the list of regular expressions that define any tetherable
2347 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
2348 * device, this list should be empty.
2349 *
2350 * @return an array of 0 or more regular expression Strings defining
2351 * what interfaces are considered tetherable bluetooth interfaces.
2352 *
Danica Chang6fdd0c62010-08-11 14:54:43 -07002353 * {@hide}
2354 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002355 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Danica Chang6fdd0c62010-08-11 14:54:43 -07002356 public String[] getTetherableBluetoothRegexs() {
2357 try {
2358 return mService.getTetherableBluetoothRegexs();
2359 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002360 throw e.rethrowFromSystemServer();
Danica Chang6fdd0c62010-08-11 14:54:43 -07002361 }
2362 }
2363
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002364 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002365 * Attempt to both alter the mode of USB and Tethering of USB. A
2366 * utility method to deal with some of the complexity of USB - will
2367 * attempt to switch to Rndis and subsequently tether the resulting
2368 * interface on {@code true} or turn off tethering and switch off
2369 * Rndis on {@code false}.
Lorenzo Colittid5427052015-10-15 16:29:00 +09002370 *
2371 * <p>This method requires the caller to hold either the
2372 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2373 * or the ability to modify system settings as determined by
2374 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002375 *
2376 * @param enable a boolean - {@code true} to enable tethering
2377 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2378 *
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002379 * {@hide}
2380 */
2381 public int setUsbTethering(boolean enable) {
2382 try {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002383 String pkgName = mContext.getOpPackageName();
2384 Log.i(TAG, "setUsbTethering caller:" + pkgName);
2385 return mService.setUsbTethering(enable, pkgName);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002386 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002387 throw e.rethrowFromSystemServer();
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002388 }
2389 }
2390
Robert Greenwalt5a735062010-03-02 17:25:02 -08002391 /** {@hide} */
2392 public static final int TETHER_ERROR_NO_ERROR = 0;
2393 /** {@hide} */
2394 public static final int TETHER_ERROR_UNKNOWN_IFACE = 1;
2395 /** {@hide} */
2396 public static final int TETHER_ERROR_SERVICE_UNAVAIL = 2;
2397 /** {@hide} */
2398 public static final int TETHER_ERROR_UNSUPPORTED = 3;
2399 /** {@hide} */
2400 public static final int TETHER_ERROR_UNAVAIL_IFACE = 4;
2401 /** {@hide} */
2402 public static final int TETHER_ERROR_MASTER_ERROR = 5;
2403 /** {@hide} */
2404 public static final int TETHER_ERROR_TETHER_IFACE_ERROR = 6;
2405 /** {@hide} */
2406 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR = 7;
2407 /** {@hide} */
2408 public static final int TETHER_ERROR_ENABLE_NAT_ERROR = 8;
2409 /** {@hide} */
2410 public static final int TETHER_ERROR_DISABLE_NAT_ERROR = 9;
2411 /** {@hide} */
2412 public static final int TETHER_ERROR_IFACE_CFG_ERROR = 10;
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002413 /** {@hide} */
2414 public static final int TETHER_ERROR_PROVISION_FAILED = 11;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002415
2416 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002417 * Get a more detailed error code after a Tethering or Untethering
2418 * request asynchronously failed.
2419 *
2420 * @param iface The name of the interface of interest
Robert Greenwalt5a735062010-03-02 17:25:02 -08002421 * @return error The error code of the last error tethering or untethering the named
2422 * interface
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002423 *
Robert Greenwalt5a735062010-03-02 17:25:02 -08002424 * {@hide}
2425 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002426 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Robert Greenwalt5a735062010-03-02 17:25:02 -08002427 public int getLastTetherError(String iface) {
2428 try {
2429 return mService.getLastTetherError(iface);
2430 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002431 throw e.rethrowFromSystemServer();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002432 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002433 }
2434
2435 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002436 * Report network connectivity status. This is currently used only
2437 * to alter status bar UI.
Paul Jensenb2748922015-05-06 11:10:18 -04002438 * <p>This method requires the caller to hold the permission
2439 * {@link android.Manifest.permission#STATUS_BAR}.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002440 *
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002441 * @param networkType The type of network you want to report on
2442 * @param percentage The quality of the connection 0 is bad, 100 is good
Chalard Jean6b1da6e2018-03-08 13:54:53 +09002443 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002444 * {@hide}
2445 */
2446 public void reportInetCondition(int networkType, int percentage) {
2447 try {
2448 mService.reportInetCondition(networkType, percentage);
2449 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002450 throw e.rethrowFromSystemServer();
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002451 }
2452 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002453
2454 /**
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002455 * Report a problem network to the framework. This provides a hint to the system
Ye Wenb87875e2014-07-21 14:19:01 -07002456 * that there might be connectivity problems on this network and may cause
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002457 * the framework to re-evaluate network connectivity and/or switch to another
2458 * network.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002459 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002460 * @param network The {@link Network} the application was attempting to use
2461 * or {@code null} to indicate the current default network.
Paul Jensenbfd17b72015-04-07 12:43:13 -04002462 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
2463 * working and non-working connectivity.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002464 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002465 @Deprecated
Robert Greenwalt9258c642014-03-26 16:47:06 -07002466 public void reportBadNetwork(Network network) {
2467 try {
Paul Jensenbfd17b72015-04-07 12:43:13 -04002468 // One of these will be ignored because it matches system's current state.
2469 // The other will trigger the necessary reevaluation.
2470 mService.reportNetworkConnectivity(network, true);
2471 mService.reportNetworkConnectivity(network, false);
2472 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002473 throw e.rethrowFromSystemServer();
Paul Jensenbfd17b72015-04-07 12:43:13 -04002474 }
2475 }
2476
2477 /**
2478 * Report to the framework whether a network has working connectivity.
2479 * This provides a hint to the system that a particular network is providing
2480 * working connectivity or not. In response the framework may re-evaluate
2481 * the network's connectivity and might take further action thereafter.
2482 *
2483 * @param network The {@link Network} the application was attempting to use
2484 * or {@code null} to indicate the current default network.
2485 * @param hasConnectivity {@code true} if the application was able to successfully access the
2486 * Internet using {@code network} or {@code false} if not.
2487 */
2488 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
2489 try {
2490 mService.reportNetworkConnectivity(network, hasConnectivity);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002491 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002492 throw e.rethrowFromSystemServer();
Robert Greenwalt9258c642014-03-26 16:47:06 -07002493 }
2494 }
2495
2496 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002497 * Set a network-independent global http proxy. This is not normally what you want
2498 * for typical HTTP proxies - they are general network dependent. However if you're
2499 * doing something unusual like general internal filtering this may be useful. On
2500 * a private network where the proxy is not accessible, you may break HTTP using this.
Paul Jensenb2748922015-05-06 11:10:18 -04002501 *
2502 * @param p A {@link ProxyInfo} object defining the new global
2503 * HTTP proxy. A {@code null} value will clear the global HTTP proxy.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002504 * @hide
Robert Greenwalt434203a2010-10-11 16:00:27 -07002505 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002506 @RequiresPermission(android.Manifest.permission.CONNECTIVITY_INTERNAL)
Jason Monk207900c2014-04-25 15:00:09 -04002507 public void setGlobalProxy(ProxyInfo p) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002508 try {
2509 mService.setGlobalProxy(p);
2510 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002511 throw e.rethrowFromSystemServer();
Robert Greenwalt434203a2010-10-11 16:00:27 -07002512 }
2513 }
2514
2515 /**
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002516 * Retrieve any network-independent global HTTP proxy.
2517 *
Jason Monk207900c2014-04-25 15:00:09 -04002518 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002519 * if no global HTTP proxy is set.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002520 * @hide
Robert Greenwalt434203a2010-10-11 16:00:27 -07002521 */
Jason Monk207900c2014-04-25 15:00:09 -04002522 public ProxyInfo getGlobalProxy() {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002523 try {
2524 return mService.getGlobalProxy();
2525 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002526 throw e.rethrowFromSystemServer();
Robert Greenwalt434203a2010-10-11 16:00:27 -07002527 }
2528 }
2529
2530 /**
Paul Jensencee9b512015-05-06 07:32:40 -04002531 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
2532 * network-specific HTTP proxy. If {@code network} is null, the
2533 * network-specific proxy returned is the proxy of the default active
2534 * network.
2535 *
2536 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
2537 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
2538 * or when {@code network} is {@code null},
2539 * the {@code ProxyInfo} for the default active network. Returns
2540 * {@code null} when no proxy applies or the caller doesn't have
2541 * permission to use {@code network}.
2542 * @hide
2543 */
2544 public ProxyInfo getProxyForNetwork(Network network) {
2545 try {
2546 return mService.getProxyForNetwork(network);
2547 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002548 throw e.rethrowFromSystemServer();
Paul Jensencee9b512015-05-06 07:32:40 -04002549 }
2550 }
2551
2552 /**
Paul Jensene0bef712014-12-10 15:12:18 -05002553 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
2554 * otherwise if this process is bound to a {@link Network} using
Paul Jensen72db88e2015-03-10 10:54:12 -04002555 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
Paul Jensene0bef712014-12-10 15:12:18 -05002556 * the default network's proxy is returned.
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002557 *
Jason Monk207900c2014-04-25 15:00:09 -04002558 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002559 * HTTP proxy is active.
Robert Greenwalt434203a2010-10-11 16:00:27 -07002560 */
Paul Jensene0bef712014-12-10 15:12:18 -05002561 public ProxyInfo getDefaultProxy() {
Paul Jensencee9b512015-05-06 07:32:40 -04002562 return getProxyForNetwork(getBoundNetworkForProcess());
Robert Greenwalt434203a2010-10-11 16:00:27 -07002563 }
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002564
2565 /**
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07002566 * Returns true if the hardware supports the given network type
2567 * else it returns false. This doesn't indicate we have coverage
2568 * or are authorized onto a network, just whether or not the
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002569 * hardware supports it. For example a GSM phone without a SIM
2570 * should still return {@code true} for mobile data, but a wifi only
2571 * tablet would return {@code false}.
2572 *
2573 * @param networkType The network type we'd like to check
2574 * @return {@code true} if supported, else {@code false}
Chalard Jean6b1da6e2018-03-08 13:54:53 +09002575 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07002576 * @hide
2577 */
Chalard Jean6b1da6e2018-03-08 13:54:53 +09002578 @Deprecated
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002579 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07002580 public boolean isNetworkSupported(int networkType) {
2581 try {
2582 return mService.isNetworkSupported(networkType);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002583 } catch (RemoteException e) {
2584 throw e.rethrowFromSystemServer();
2585 }
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07002586 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002587
2588 /**
2589 * Returns if the currently active data network is metered. A network is
2590 * classified as metered when the user is sensitive to heavy data usage on
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002591 * that connection due to monetary costs, data limitations or
2592 * battery/performance issues. You should check this before doing large
2593 * data transfers, and warn the user or delay the operation until another
2594 * network is available.
2595 *
2596 * @return {@code true} if large transfers should be avoided, otherwise
2597 * {@code false}.
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002598 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002599 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002600 public boolean isActiveNetworkMetered() {
2601 try {
2602 return mService.isActiveNetworkMetered();
2603 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002604 throw e.rethrowFromSystemServer();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002605 }
2606 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002607
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002608 /**
2609 * If the LockdownVpn mechanism is enabled, updates the vpn
2610 * with a reload of its profile.
2611 *
2612 * @return a boolean with {@code} indicating success
2613 *
2614 * <p>This method can only be called by the system UID
2615 * {@hide}
2616 */
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002617 public boolean updateLockdownVpn() {
2618 try {
2619 return mService.updateLockdownVpn();
2620 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002621 throw e.rethrowFromSystemServer();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002622 }
2623 }
Irfan Sheriffda6da092012-08-16 12:49:23 -07002624
2625 /**
Wink Saville948282b2013-08-29 08:55:16 -07002626 * Check mobile provisioning.
Wink Savilleab9321d2013-06-29 21:10:57 -07002627 *
Wink Savilleab9321d2013-06-29 21:10:57 -07002628 * @param suggestedTimeOutMs, timeout in milliseconds
Wink Savilleab9321d2013-06-29 21:10:57 -07002629 *
2630 * @return time out that will be used, maybe less that suggestedTimeOutMs
2631 * -1 if an error.
2632 *
2633 * {@hide}
2634 */
Wink Saville948282b2013-08-29 08:55:16 -07002635 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Wink Savilleab9321d2013-06-29 21:10:57 -07002636 int timeOutMs = -1;
2637 try {
Wink Saville948282b2013-08-29 08:55:16 -07002638 timeOutMs = mService.checkMobileProvisioning(suggestedTimeOutMs);
Wink Savilleab9321d2013-06-29 21:10:57 -07002639 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002640 throw e.rethrowFromSystemServer();
Wink Savilleab9321d2013-06-29 21:10:57 -07002641 }
2642 return timeOutMs;
2643 }
Robert Greenwalte182bfe2013-07-16 12:06:09 -07002644
2645 /**
Wink Saville42d4f082013-07-20 20:31:59 -07002646 * Get the mobile provisioning url.
Robert Greenwalte182bfe2013-07-16 12:06:09 -07002647 * {@hide}
2648 */
2649 public String getMobileProvisioningUrl() {
2650 try {
2651 return mService.getMobileProvisioningUrl();
2652 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002653 throw e.rethrowFromSystemServer();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07002654 }
Robert Greenwalte182bfe2013-07-16 12:06:09 -07002655 }
Wink Saville42d4f082013-07-20 20:31:59 -07002656
2657 /**
Wink Saville948282b2013-08-29 08:55:16 -07002658 * Set sign in error notification to visible or in visible
2659 *
2660 * @param visible
2661 * @param networkType
2662 *
2663 * {@hide}
Paul Jensen3541e9f2015-03-18 12:23:02 -04002664 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
Wink Saville948282b2013-08-29 08:55:16 -07002665 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07002666 @Deprecated
Wink Saville948282b2013-08-29 08:55:16 -07002667 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04002668 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07002669 try {
Paul Jensen89e0f092014-09-15 15:59:36 -04002670 mService.setProvisioningNotificationVisible(visible, networkType, action);
Wink Saville948282b2013-08-29 08:55:16 -07002671 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002672 throw e.rethrowFromSystemServer();
Wink Saville948282b2013-08-29 08:55:16 -07002673 }
2674 }
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07002675
2676 /**
2677 * Set the value for enabling/disabling airplane mode
2678 *
2679 * @param enable whether to enable airplane mode or not
2680 *
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07002681 * @hide
2682 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06002683 @RequiresPermission(android.Manifest.permission.CONNECTIVITY_INTERNAL)
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07002684 public void setAirplaneMode(boolean enable) {
2685 try {
2686 mService.setAirplaneMode(enable);
2687 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002688 throw e.rethrowFromSystemServer();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07002689 }
2690 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002691
2692 /** {@hide} */
Robert Greenwalta67be032014-05-16 15:49:14 -07002693 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07002694 try {
Robert Greenwalta67be032014-05-16 15:49:14 -07002695 mService.registerNetworkFactory(messenger, name);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002696 } catch (RemoteException e) {
2697 throw e.rethrowFromSystemServer();
2698 }
Robert Greenwalta67be032014-05-16 15:49:14 -07002699 }
2700
2701 /** {@hide} */
2702 public void unregisterNetworkFactory(Messenger messenger) {
2703 try {
2704 mService.unregisterNetworkFactory(messenger);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002705 } catch (RemoteException e) {
2706 throw e.rethrowFromSystemServer();
2707 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002708 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002709
Paul Jensen31a94f42015-02-13 14:18:39 -05002710 /**
2711 * @hide
2712 * Register a NetworkAgent with ConnectivityService.
2713 * @return NetID corresponding to NetworkAgent.
2714 */
2715 public int registerNetworkAgent(Messenger messenger, NetworkInfo ni, LinkProperties lp,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07002716 NetworkCapabilities nc, int score, NetworkMisc misc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002717 try {
Paul Jensen31a94f42015-02-13 14:18:39 -05002718 return mService.registerNetworkAgent(messenger, ni, lp, nc, score, misc);
2719 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002720 throw e.rethrowFromSystemServer();
Paul Jensen31a94f42015-02-13 14:18:39 -05002721 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002722 }
2723
Robert Greenwalt9258c642014-03-26 16:47:06 -07002724 /**
Hugo Benichidafed3d2017-03-06 09:17:06 +09002725 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
2726 * changes. Should be extended by applications wanting notifications.
2727 *
2728 * A {@code NetworkCallback} is registered by calling
2729 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2730 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
Hugo Benichica867dc2018-02-07 21:17:43 +09002731 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
Hugo Benichidafed3d2017-03-06 09:17:06 +09002732 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
2733 * A {@code NetworkCallback} should be registered at most once at any time.
2734 * A {@code NetworkCallback} that has been unregistered can be registered again.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002735 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07002736 public static class NetworkCallback {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002737 /**
Lorenzo Colitti07086932015-04-24 12:23:24 +09002738 * Called when the framework connects to a new network to evaluate whether it satisfies this
2739 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
2740 * callback. There is no guarantee that this new network will satisfy any requests, or that
2741 * the network will stay connected for longer than the time necessary to evaluate it.
2742 * <p>
2743 * Most applications <b>should not</b> act on this callback, and should instead use
2744 * {@link #onAvailable}. This callback is intended for use by applications that can assist
2745 * the framework in properly evaluating the network &mdash; for example, an application that
2746 * can automatically log in to a captive portal without user intervention.
2747 *
2748 * @param network The {@link Network} of the network that is being evaluated.
Lorenzo Colitti66276122015-06-11 14:27:17 +09002749 *
2750 * @hide
Robert Greenwalt7b816022014-04-18 15:25:25 -07002751 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07002752 public void onPreCheck(Network network) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07002753
2754 /**
Lorenzo Colitti07086932015-04-24 12:23:24 +09002755 * Called when the framework connects and has declared a new network ready for use.
Robert Greenwalt6078b502014-06-11 16:05:07 -07002756 * This callback may be called more than once if the {@link Network} that is
2757 * satisfying the request changes.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002758 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002759 * @param network The {@link Network} of the satisfying network.
Chalard Jean804b8fb2018-01-30 22:41:41 +09002760 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
2761 * @param linkProperties The {@link LinkProperties} of the satisfying network.
2762 * @hide
2763 */
2764 public void onAvailable(Network network, NetworkCapabilities networkCapabilities,
2765 LinkProperties linkProperties) {
2766 // Internally only this method is called when a new network is available, and
2767 // it calls the callback in the same way and order that older versions used
2768 // to call so as not to change the behavior.
2769 onAvailable(network);
2770 if (!networkCapabilities.hasCapability(
2771 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
2772 onNetworkSuspended(network);
2773 }
2774 onCapabilitiesChanged(network, networkCapabilities);
2775 onLinkPropertiesChanged(network, linkProperties);
2776 }
2777
2778 /**
2779 * Called when the framework connects and has declared a new network ready for use.
2780 * This callback may be called more than once if the {@link Network} that is
2781 * satisfying the request changes. This will always immediately be followed by a
2782 * call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} then by a
2783 * call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}.
2784 *
2785 * @param network The {@link Network} of the satisfying network.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002786 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07002787 public void onAvailable(Network network) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07002788
2789 /**
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002790 * Called when the network is about to be disconnected. Often paired with an
Robert Greenwalt6078b502014-06-11 16:05:07 -07002791 * {@link NetworkCallback#onAvailable} call with the new replacement network
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002792 * for graceful handover. This may not be called if we have a hard loss
2793 * (loss without warning). This may be followed by either a
Robert Greenwalt6078b502014-06-11 16:05:07 -07002794 * {@link NetworkCallback#onLost} call or a
2795 * {@link NetworkCallback#onAvailable} call for this network depending
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002796 * on whether we lose or regain it.
2797 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07002798 * @param network The {@link Network} that is about to be disconnected.
2799 * @param maxMsToLive The time in ms the framework will attempt to keep the
2800 * network connected. Note that the network may suffer a
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002801 * hard loss at any time.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002802 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07002803 public void onLosing(Network network, int maxMsToLive) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07002804
2805 /**
2806 * Called when the framework has a hard loss of the network or when the
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002807 * graceful failure ends.
2808 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002809 * @param network The {@link Network} lost.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002810 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07002811 public void onLost(Network network) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07002812
2813 /**
Etan Cohenaebf17e2017-03-01 12:47:28 -08002814 * Called if no network is found in the timeout time specified in
Hugo Benichi0eec03f2017-05-15 15:15:33 +09002815 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call. This callback is not
Etan Cohenaebf17e2017-03-01 12:47:28 -08002816 * called for the version of {@link #requestNetwork(NetworkRequest, NetworkCallback)}
2817 * without timeout. When this callback is invoked the associated
2818 * {@link NetworkRequest} will have already been removed and released, as if
2819 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002820 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07002821 public void onUnavailable() {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07002822
2823 /**
2824 * Called when the network the framework connected to for this request
2825 * changes capabilities but still satisfies the stated need.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002826 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002827 * @param network The {@link Network} whose capabilities have changed.
Chalard Jean804b8fb2018-01-30 22:41:41 +09002828 * @param networkCapabilities The new {@link android.net.NetworkCapabilities} for this
2829 * network.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002830 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07002831 public void onCapabilitiesChanged(Network network,
Robert Greenwalt7b816022014-04-18 15:25:25 -07002832 NetworkCapabilities networkCapabilities) {}
2833
2834 /**
2835 * Called when the network the framework connected to for this request
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002836 * changes {@link LinkProperties}.
2837 *
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07002838 * @param network The {@link Network} whose link properties have changed.
2839 * @param linkProperties The new {@link LinkProperties} for this network.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002840 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07002841 public void onLinkPropertiesChanged(Network network, LinkProperties linkProperties) {}
Robert Greenwalt7b816022014-04-18 15:25:25 -07002842
Robert Greenwalt8d482522015-06-24 13:23:42 -07002843 /**
2844 * Called when the network the framework connected to for this request
Chalard Jean804b8fb2018-01-30 22:41:41 +09002845 * goes into {@link NetworkInfo.State#SUSPENDED}.
Robert Greenwalt8d482522015-06-24 13:23:42 -07002846 * This generally means that while the TCP connections are still live,
2847 * temporarily network data fails to transfer. Specifically this is used
2848 * on cellular networks to mask temporary outages when driving through
2849 * a tunnel, etc.
2850 * @hide
2851 */
2852 public void onNetworkSuspended(Network network) {}
2853
2854 /**
2855 * Called when the network the framework connected to for this request
Chalard Jean804b8fb2018-01-30 22:41:41 +09002856 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
2857 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
Robert Greenwalt8d482522015-06-24 13:23:42 -07002858 * @hide
2859 */
2860 public void onNetworkResumed(Network network) {}
2861
Robert Greenwalt6078b502014-06-11 16:05:07 -07002862 private NetworkRequest networkRequest;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002863 }
2864
Hugo Benichicb883232017-05-11 13:16:17 +09002865 /**
2866 * Constant error codes used by ConnectivityService to communicate about failures and errors
2867 * across a Binder boundary.
2868 * @hide
2869 */
2870 public interface Errors {
2871 static int TOO_MANY_REQUESTS = 1;
2872 }
2873
2874 /** @hide */
2875 public static class TooManyRequestsException extends RuntimeException {}
2876
2877 private static RuntimeException convertServiceException(ServiceSpecificException e) {
2878 switch (e.errorCode) {
2879 case Errors.TOO_MANY_REQUESTS:
2880 return new TooManyRequestsException();
2881 default:
2882 Log.w(TAG, "Unknown service error code " + e.errorCode);
2883 return new RuntimeException(e);
2884 }
2885 }
2886
Robert Greenwalt9258c642014-03-26 16:47:06 -07002887 private static final int BASE = Protocol.BASE_CONNECTIVITY_MANAGER;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002888 /** @hide */
Robert Greenwalt8d482522015-06-24 13:23:42 -07002889 public static final int CALLBACK_PRECHECK = BASE + 1;
2890 /** @hide */
2891 public static final int CALLBACK_AVAILABLE = BASE + 2;
2892 /** @hide arg1 = TTL */
2893 public static final int CALLBACK_LOSING = BASE + 3;
2894 /** @hide */
2895 public static final int CALLBACK_LOST = BASE + 4;
2896 /** @hide */
2897 public static final int CALLBACK_UNAVAIL = BASE + 5;
2898 /** @hide */
2899 public static final int CALLBACK_CAP_CHANGED = BASE + 6;
2900 /** @hide */
2901 public static final int CALLBACK_IP_CHANGED = BASE + 7;
Robert Greenwalt562cc542014-05-15 18:07:26 -07002902 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Hugo Benichidba33db2017-03-23 22:40:44 +09002903 private static final int EXPIRE_LEGACY_REQUEST = BASE + 8;
Robert Greenwalt8d482522015-06-24 13:23:42 -07002904 /** @hide */
Hugo Benichidba33db2017-03-23 22:40:44 +09002905 public static final int CALLBACK_SUSPENDED = BASE + 9;
Robert Greenwalt8d482522015-06-24 13:23:42 -07002906 /** @hide */
Hugo Benichidba33db2017-03-23 22:40:44 +09002907 public static final int CALLBACK_RESUMED = BASE + 10;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002908
Erik Kline57faba92015-11-25 12:49:38 +09002909 /** @hide */
2910 public static String getCallbackName(int whichCallback) {
2911 switch (whichCallback) {
2912 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
2913 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
2914 case CALLBACK_LOSING: return "CALLBACK_LOSING";
2915 case CALLBACK_LOST: return "CALLBACK_LOST";
2916 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
2917 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
2918 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
Erik Kline57faba92015-11-25 12:49:38 +09002919 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
2920 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
2921 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
2922 default:
2923 return Integer.toString(whichCallback);
2924 }
2925 }
2926
Robert Greenwalt562cc542014-05-15 18:07:26 -07002927 private class CallbackHandler extends Handler {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002928 private static final String TAG = "ConnectivityManager.CallbackHandler";
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07002929 private static final boolean DBG = false;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002930
Hugo Benichid42650f2016-07-06 22:53:17 +09002931 CallbackHandler(Looper looper) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002932 super(looper);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002933 }
2934
Hugo Benichi2583ef02017-02-02 17:02:36 +09002935 CallbackHandler(Handler handler) {
Hugo Benichie7678512017-05-09 15:19:01 +09002936 this(Preconditions.checkNotNull(handler, "Handler cannot be null.").getLooper());
Hugo Benichi2583ef02017-02-02 17:02:36 +09002937 }
2938
Robert Greenwalt9258c642014-03-26 16:47:06 -07002939 @Override
2940 public void handleMessage(Message message) {
Hugo Benichi2c684522017-05-09 14:36:02 +09002941 if (message.what == EXPIRE_LEGACY_REQUEST) {
2942 expireRequest((NetworkCapabilities) message.obj, message.arg1);
2943 return;
2944 }
2945
2946 final NetworkRequest request = getObject(message, NetworkRequest.class);
2947 final Network network = getObject(message, Network.class);
2948 final NetworkCallback callback;
2949 synchronized (sCallbacks) {
2950 callback = sCallbacks.get(request);
2951 }
Lorenzo Colittifcfa7d92016-03-01 22:56:37 +09002952 if (DBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09002953 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
Lorenzo Colittifcfa7d92016-03-01 22:56:37 +09002954 }
Hugo Benichi2c684522017-05-09 14:36:02 +09002955 if (callback == null) {
2956 Log.w(TAG, "callback not found for " + getCallbackName(message.what) + " message");
2957 return;
2958 }
2959
Robert Greenwalt9258c642014-03-26 16:47:06 -07002960 switch (message.what) {
2961 case CALLBACK_PRECHECK: {
Hugo Benichi2c684522017-05-09 14:36:02 +09002962 callback.onPreCheck(network);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002963 break;
2964 }
2965 case CALLBACK_AVAILABLE: {
Chalard Jean804b8fb2018-01-30 22:41:41 +09002966 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
2967 LinkProperties lp = getObject(message, LinkProperties.class);
2968 callback.onAvailable(network, cap, lp);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002969 break;
2970 }
2971 case CALLBACK_LOSING: {
Hugo Benichi2c684522017-05-09 14:36:02 +09002972 callback.onLosing(network, message.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002973 break;
2974 }
2975 case CALLBACK_LOST: {
Hugo Benichi2c684522017-05-09 14:36:02 +09002976 callback.onLost(network);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002977 break;
2978 }
2979 case CALLBACK_UNAVAIL: {
Hugo Benichi2c684522017-05-09 14:36:02 +09002980 callback.onUnavailable();
Robert Greenwalt9258c642014-03-26 16:47:06 -07002981 break;
2982 }
2983 case CALLBACK_CAP_CHANGED: {
Hugo Benichi2c684522017-05-09 14:36:02 +09002984 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
2985 callback.onCapabilitiesChanged(network, cap);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002986 break;
2987 }
2988 case CALLBACK_IP_CHANGED: {
Hugo Benichi2c684522017-05-09 14:36:02 +09002989 LinkProperties lp = getObject(message, LinkProperties.class);
2990 callback.onLinkPropertiesChanged(network, lp);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002991 break;
2992 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07002993 case CALLBACK_SUSPENDED: {
Hugo Benichi2c684522017-05-09 14:36:02 +09002994 callback.onNetworkSuspended(network);
Robert Greenwalt8d482522015-06-24 13:23:42 -07002995 break;
2996 }
2997 case CALLBACK_RESUMED: {
Hugo Benichi2c684522017-05-09 14:36:02 +09002998 callback.onNetworkResumed(network);
Robert Greenwalt562cc542014-05-15 18:07:26 -07002999 break;
3000 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003001 }
3002 }
3003
Hugo Benichid42650f2016-07-06 22:53:17 +09003004 private <T> T getObject(Message msg, Class<T> c) {
3005 return (T) msg.getData().getParcelable(c.getSimpleName());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003006 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003007 }
3008
Hugo Benichi2583ef02017-02-02 17:02:36 +09003009 private CallbackHandler getDefaultHandler() {
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003010 synchronized (sCallbacks) {
3011 if (sCallbackHandler == null) {
3012 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003013 }
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003014 return sCallbackHandler;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003015 }
3016 }
3017
Hugo Benichi6f260f32017-02-03 14:18:44 +09003018 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
3019 private static CallbackHandler sCallbackHandler;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003020
Hugo Benichi6f260f32017-02-03 14:18:44 +09003021 private static final int LISTEN = 1;
3022 private static final int REQUEST = 2;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003023
Hugo Benichi6f260f32017-02-03 14:18:44 +09003024 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
3025 int timeoutMs, int action, int legacyType, CallbackHandler handler) {
Hugo Benichie7678512017-05-09 15:19:01 +09003026 checkCallbackNotNull(callback);
Hugo Benichidafed3d2017-03-06 09:17:06 +09003027 Preconditions.checkArgument(action == REQUEST || need != null, "null NetworkCapabilities");
Hugo Benichid42650f2016-07-06 22:53:17 +09003028 final NetworkRequest request;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003029 try {
Hugo Benichid42650f2016-07-06 22:53:17 +09003030 synchronized(sCallbacks) {
Hugo Benichi31c176d2017-06-17 13:14:12 +09003031 if (callback.networkRequest != null
3032 && callback.networkRequest != ALREADY_UNREGISTERED) {
Hugo Benichidafed3d2017-03-06 09:17:06 +09003033 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
3034 // and requests (http://b/20701525).
3035 Log.e(TAG, "NetworkCallback was already registered");
3036 }
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003037 Messenger messenger = new Messenger(handler);
Hugo Benichid42650f2016-07-06 22:53:17 +09003038 Binder binder = new Binder();
Paul Jensen7221cc32014-06-27 11:05:32 -04003039 if (action == LISTEN) {
Hugo Benichid42650f2016-07-06 22:53:17 +09003040 request = mService.listenForNetwork(need, messenger, binder);
Paul Jensen7221cc32014-06-27 11:05:32 -04003041 } else {
Hugo Benichid42650f2016-07-06 22:53:17 +09003042 request = mService.requestNetwork(
3043 need, messenger, timeoutMs, binder, legacyType);
Paul Jensen7221cc32014-06-27 11:05:32 -04003044 }
Hugo Benichid42650f2016-07-06 22:53:17 +09003045 if (request != null) {
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003046 sCallbacks.put(request, callback);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003047 }
Hugo Benichi7724cdd2016-07-07 10:15:56 +09003048 callback.networkRequest = request;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003049 }
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003050 } catch (RemoteException e) {
3051 throw e.rethrowFromSystemServer();
Hugo Benichicb883232017-05-11 13:16:17 +09003052 } catch (ServiceSpecificException e) {
3053 throw convertServiceException(e);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003054 }
Hugo Benichid42650f2016-07-06 22:53:17 +09003055 return request;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003056 }
3057
3058 /**
Erik Klinea2d29402016-03-16 15:31:39 +09003059 * Helper function to request a network with a particular legacy type.
Lorenzo Colitti7de289f2015-11-25 12:00:52 +09003060 *
3061 * This is temporarily public @hide so it can be called by system code that uses the
3062 * NetworkRequest API to request networks but relies on CONNECTIVITY_ACTION broadcasts for
3063 * instead network notifications.
3064 *
3065 * TODO: update said system code to rely on NetworkCallbacks and make this method private.
3066 *
3067 * @hide
3068 */
Lorenzo Colittid1179462015-11-25 15:47:14 +09003069 public void requestNetwork(NetworkRequest request, NetworkCallback networkCallback,
Hugo Benichi2583ef02017-02-02 17:02:36 +09003070 int timeoutMs, int legacyType, Handler handler) {
3071 CallbackHandler cbHandler = new CallbackHandler(handler);
3072 NetworkCapabilities nc = request.networkCapabilities;
3073 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
Lorenzo Colitti7de289f2015-11-25 12:00:52 +09003074 }
3075
3076 /**
Lorenzo Colittie285b432015-04-23 15:32:42 +09003077 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003078 *
3079 * This {@link NetworkRequest} will live until released via
Etan Cohenaebf17e2017-03-01 12:47:28 -08003080 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits. A
3081 * version of the method which takes a timeout is
Hugo Benichi0eec03f2017-05-15 15:15:33 +09003082 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003083 * Status of the request can be followed by listening to the various
Robert Greenwalt6078b502014-06-11 16:05:07 -07003084 * callbacks described in {@link NetworkCallback}. The {@link Network}
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003085 * can be used to direct traffic to the network.
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003086 * <p>It is presently unsupported to request a network with mutable
3087 * {@link NetworkCapabilities} such as
3088 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3089 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3090 * as these {@code NetworkCapabilities} represent states that a particular
3091 * network may never attain, and whether a network will attain these states
3092 * is unknown prior to bringing up the network so the framework does not
3093 * know how to go about satisfing a request with these capabilities.
Lorenzo Colittid5427052015-10-15 16:29:00 +09003094 *
3095 * <p>This method requires the caller to hold either the
3096 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3097 * or the ability to modify system settings as determined by
3098 * {@link android.provider.Settings.System#canWrite}.</p>
Robert Greenwalt9258c642014-03-26 16:47:06 -07003099 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07003100 * @param request {@link NetworkRequest} describing this request.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003101 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3102 * the callback must not be shared - it uniquely specifies this request.
3103 * The callback is invoked on the default internal Handler.
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003104 * @throws IllegalArgumentException if {@code request} specifies any mutable
3105 * {@code NetworkCapabilities}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003106 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07003107 public void requestNetwork(NetworkRequest request, NetworkCallback networkCallback) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003108 requestNetwork(request, networkCallback, getDefaultHandler());
3109 }
3110
3111 /**
3112 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
3113 *
3114 * This {@link NetworkRequest} will live until released via
Etan Cohenaebf17e2017-03-01 12:47:28 -08003115 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits. A
3116 * version of the method which takes a timeout is
Hugo Benichi0eec03f2017-05-15 15:15:33 +09003117 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003118 * Status of the request can be followed by listening to the various
3119 * callbacks described in {@link NetworkCallback}. The {@link Network}
3120 * can be used to direct traffic to the network.
3121 * <p>It is presently unsupported to request a network with mutable
3122 * {@link NetworkCapabilities} such as
3123 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3124 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3125 * as these {@code NetworkCapabilities} represent states that a particular
3126 * network may never attain, and whether a network will attain these states
3127 * is unknown prior to bringing up the network so the framework does not
3128 * know how to go about satisfing a request with these capabilities.
3129 *
3130 * <p>This method requires the caller to hold either the
3131 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3132 * or the ability to modify system settings as determined by
3133 * {@link android.provider.Settings.System#canWrite}.</p>
3134 *
3135 * @param request {@link NetworkRequest} describing this request.
3136 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3137 * the callback must not be shared - it uniquely specifies this request.
3138 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
3139 * @throws IllegalArgumentException if {@code request} specifies any mutable
3140 * {@code NetworkCapabilities}.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003141 */
3142 public void requestNetwork(
3143 NetworkRequest request, NetworkCallback networkCallback, Handler handler) {
3144 int legacyType = inferLegacyTypeForNetworkCapabilities(request.networkCapabilities);
3145 CallbackHandler cbHandler = new CallbackHandler(handler);
3146 requestNetwork(request, networkCallback, 0, legacyType, cbHandler);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003147 }
3148
3149 /**
Etan Cohenaebf17e2017-03-01 12:47:28 -08003150 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
3151 * by a timeout.
3152 *
3153 * This function behaves identically to the non-timed-out version
3154 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
3155 * is not found within the given time (in milliseconds) the
3156 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
3157 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
3158 * not have to be released if timed-out (it is automatically released). Unregistering a
3159 * request that timed out is not an error.
3160 *
3161 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
3162 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
3163 * for that purpose. Calling this method will attempt to bring up the requested network.
3164 *
3165 * <p>This method requires the caller to hold either the
3166 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3167 * or the ability to modify system settings as determined by
3168 * {@link android.provider.Settings.System#canWrite}.</p>
3169 *
3170 * @param request {@link NetworkRequest} describing this request.
Lorenzo Colitti15fd4392017-04-28 00:56:30 +09003171 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3172 * the callback must not be shared - it uniquely specifies this request.
Etan Cohenaebf17e2017-03-01 12:47:28 -08003173 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3174 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
3175 * be a positive value (i.e. >0).
Etan Cohenaebf17e2017-03-01 12:47:28 -08003176 */
Lorenzo Colitti15fd4392017-04-28 00:56:30 +09003177 public void requestNetwork(NetworkRequest request, NetworkCallback networkCallback,
3178 int timeoutMs) {
Hugo Benichie7678512017-05-09 15:19:01 +09003179 checkTimeout(timeoutMs);
Hugo Benichi2583ef02017-02-02 17:02:36 +09003180 int legacyType = inferLegacyTypeForNetworkCapabilities(request.networkCapabilities);
Erik Klineb583b032017-02-22 12:58:24 +09003181 requestNetwork(request, networkCallback, timeoutMs, legacyType, getDefaultHandler());
Hugo Benichi2583ef02017-02-02 17:02:36 +09003182 }
3183
Hugo Benichi2583ef02017-02-02 17:02:36 +09003184 /**
3185 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
3186 * by a timeout.
3187 *
3188 * This function behaves identically to the non-timedout version, but if a suitable
3189 * network is not found within the given time (in milliseconds) the
Etan Cohenaebf17e2017-03-01 12:47:28 -08003190 * {@link NetworkCallback#onUnavailable} callback is called. The request can still be
3191 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
3192 * not have to be released if timed-out (it is automatically released). Unregistering a
3193 * request that timed out is not an error.
3194 *
3195 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
3196 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
3197 * for that purpose. Calling this method will attempt to bring up the requested network.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003198 *
3199 * <p>This method requires the caller to hold either the
3200 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3201 * or the ability to modify system settings as determined by
3202 * {@link android.provider.Settings.System#canWrite}.</p>
3203 *
3204 * @param request {@link NetworkRequest} describing this request.
Etan Cohenaebf17e2017-03-01 12:47:28 -08003205 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
3206 * the callback must not be shared - it uniquely specifies this request.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003207 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Lorenzo Colitti15fd4392017-04-28 00:56:30 +09003208 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
3209 * before {@link NetworkCallback#onUnavailable} is called.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003210 */
Lorenzo Colitti15fd4392017-04-28 00:56:30 +09003211 public void requestNetwork(NetworkRequest request, NetworkCallback networkCallback,
3212 Handler handler, int timeoutMs) {
Hugo Benichie7678512017-05-09 15:19:01 +09003213 checkTimeout(timeoutMs);
Hugo Benichi2583ef02017-02-02 17:02:36 +09003214 int legacyType = inferLegacyTypeForNetworkCapabilities(request.networkCapabilities);
3215 CallbackHandler cbHandler = new CallbackHandler(handler);
3216 requestNetwork(request, networkCallback, timeoutMs, legacyType, cbHandler);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003217 }
3218
3219 /**
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003220 * The lookup key for a {@link Network} object included with the intent after
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003221 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003222 * {@link android.content.Intent#getParcelableExtra(String)}.
Jeremy Joslinfcde58f2015-02-11 16:51:13 -08003223 * <p>
Paul Jensen72db88e2015-03-10 10:54:12 -04003224 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
3225 * then you must get a ConnectivityManager instance before doing so.
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003226 */
Erik Kline90e93072014-11-19 12:12:24 +09003227 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003228
3229 /**
Robert Greenwalt6078b502014-06-11 16:05:07 -07003230 * The lookup key for a {@link NetworkRequest} object included with the intent after
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003231 * successfully finding a network for the applications request. Retrieve it with
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003232 * {@link android.content.Intent#getParcelableExtra(String)}.
3233 */
Erik Kline90e93072014-11-19 12:12:24 +09003234 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003235
3236
3237 /**
Lorenzo Colittie285b432015-04-23 15:32:42 +09003238 * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003239 *
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003240 * This function behaves identically to the version that takes a NetworkCallback, but instead
Robert Greenwalt6078b502014-06-11 16:05:07 -07003241 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003242 * the request may outlive the calling application and get called back when a suitable
3243 * network is found.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003244 * <p>
3245 * The operation is an Intent broadcast that goes to a broadcast receiver that
3246 * you registered with {@link Context#registerReceiver} or through the
3247 * &lt;receiver&gt; tag in an AndroidManifest.xml file
3248 * <p>
3249 * The operation Intent is delivered with two extras, a {@link Network} typed
Erik Kline90e93072014-11-19 12:12:24 +09003250 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
3251 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
Robert Greenwalt9258c642014-03-26 16:47:06 -07003252 * the original requests parameters. It is important to create a new,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003253 * {@link NetworkCallback} based request before completing the processing of the
Robert Greenwalt9258c642014-03-26 16:47:06 -07003254 * Intent to reserve the network or it will be released shortly after the Intent
3255 * is processed.
3256 * <p>
Paul Jensen694f2b82015-06-17 14:15:39 -04003257 * If there is already a request for this Intent registered (with the equality of
Robert Greenwalt9258c642014-03-26 16:47:06 -07003258 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
Robert Greenwaltd19c41c2014-05-18 23:07:25 -07003259 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003260 * <p>
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003261 * The request may be released normally by calling
3262 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003263 * <p>It is presently unsupported to request a network with either
3264 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3265 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
3266 * as these {@code NetworkCapabilities} represent states that a particular
3267 * network may never attain, and whether a network will attain these states
3268 * is unknown prior to bringing up the network so the framework does not
3269 * know how to go about satisfing a request with these capabilities.
Lorenzo Colittid5427052015-10-15 16:29:00 +09003270 *
3271 * <p>This method requires the caller to hold either the
3272 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3273 * or the ability to modify system settings as determined by
3274 * {@link android.provider.Settings.System#canWrite}.</p>
3275 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07003276 * @param request {@link NetworkRequest} describing this request.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003277 * @param operation Action to perform when the network is available (corresponds
Robert Greenwalt6078b502014-06-11 16:05:07 -07003278 * to the {@link NetworkCallback#onAvailable} call. Typically
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003279 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003280 * @throws IllegalArgumentException if {@code request} contains either
3281 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
3282 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003283 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07003284 public void requestNetwork(NetworkRequest request, PendingIntent operation) {
Hugo Benichie7678512017-05-09 15:19:01 +09003285 checkPendingIntentNotNull(operation);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003286 try {
Robert Greenwalt6078b502014-06-11 16:05:07 -07003287 mService.pendingRequestForNetwork(request.networkCapabilities, operation);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003288 } catch (RemoteException e) {
3289 throw e.rethrowFromSystemServer();
Hugo Benichicb883232017-05-11 13:16:17 +09003290 } catch (ServiceSpecificException e) {
3291 throw convertServiceException(e);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003292 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003293 }
3294
3295 /**
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003296 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
3297 * <p>
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09003298 * This method has the same behavior as
3299 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003300 * releasing network resources and disconnecting.
3301 *
3302 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
3303 * PendingIntent passed to
3304 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
3305 * corresponding NetworkRequest you'd like to remove. Cannot be null.
3306 */
3307 public void releaseNetworkRequest(PendingIntent operation) {
Hugo Benichie7678512017-05-09 15:19:01 +09003308 checkPendingIntentNotNull(operation);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003309 try {
3310 mService.releasePendingNetworkRequest(operation);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003311 } catch (RemoteException e) {
3312 throw e.rethrowFromSystemServer();
3313 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003314 }
3315
Hugo Benichie7678512017-05-09 15:19:01 +09003316 private static void checkPendingIntentNotNull(PendingIntent intent) {
3317 Preconditions.checkNotNull(intent, "PendingIntent cannot be null.");
3318 }
3319
3320 private static void checkCallbackNotNull(NetworkCallback callback) {
3321 Preconditions.checkNotNull(callback, "null NetworkCallback");
3322 }
3323
3324 private static void checkTimeout(int timeoutMs) {
3325 Preconditions.checkArgumentPositive(timeoutMs, "timeoutMs must be strictly positive.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003326 }
3327
3328 /**
Robert Greenwalt9258c642014-03-26 16:47:06 -07003329 * Registers to receive notifications about all networks which satisfy the given
Robert Greenwalt6078b502014-06-11 16:05:07 -07003330 * {@link NetworkRequest}. The callbacks will continue to be called until
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09003331 * either the application exits or link #unregisterNetworkCallback(NetworkCallback)} is called.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003332 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07003333 * @param request {@link NetworkRequest} describing this request.
3334 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
3335 * networks change state.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003336 * The callback is invoked on the default internal Handler.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003337 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003338 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Robert Greenwalt6078b502014-06-11 16:05:07 -07003339 public void registerNetworkCallback(NetworkRequest request, NetworkCallback networkCallback) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003340 registerNetworkCallback(request, networkCallback, getDefaultHandler());
3341 }
3342
3343 /**
3344 * Registers to receive notifications about all networks which satisfy the given
3345 * {@link NetworkRequest}. The callbacks will continue to be called until
3346 * either the application exits or link #unregisterNetworkCallback(NetworkCallback)} is called.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003347 *
3348 * @param request {@link NetworkRequest} describing this request.
3349 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
3350 * networks change state.
3351 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003352 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003353 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Hugo Benichi2583ef02017-02-02 17:02:36 +09003354 public void registerNetworkCallback(
3355 NetworkRequest request, NetworkCallback networkCallback, Handler handler) {
3356 CallbackHandler cbHandler = new CallbackHandler(handler);
3357 NetworkCapabilities nc = request.networkCapabilities;
3358 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003359 }
3360
3361 /**
Paul Jensen694f2b82015-06-17 14:15:39 -04003362 * Registers a PendingIntent to be sent when a network is available which satisfies the given
3363 * {@link NetworkRequest}.
3364 *
3365 * This function behaves identically to the version that takes a NetworkCallback, but instead
3366 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
3367 * the request may outlive the calling application and get called back when a suitable
3368 * network is found.
3369 * <p>
3370 * The operation is an Intent broadcast that goes to a broadcast receiver that
3371 * you registered with {@link Context#registerReceiver} or through the
3372 * &lt;receiver&gt; tag in an AndroidManifest.xml file
3373 * <p>
3374 * The operation Intent is delivered with two extras, a {@link Network} typed
3375 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
3376 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
3377 * the original requests parameters.
3378 * <p>
3379 * If there is already a request for this Intent registered (with the equality of
3380 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
3381 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
3382 * <p>
3383 * The request may be released normally by calling
Paul Jensenf2c1cfe2015-06-30 14:29:18 -04003384 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
Paul Jensen694f2b82015-06-17 14:15:39 -04003385 * @param request {@link NetworkRequest} describing this request.
3386 * @param operation Action to perform when the network is available (corresponds
3387 * to the {@link NetworkCallback#onAvailable} call. Typically
3388 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
3389 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003390 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Paul Jensen694f2b82015-06-17 14:15:39 -04003391 public void registerNetworkCallback(NetworkRequest request, PendingIntent operation) {
Hugo Benichie7678512017-05-09 15:19:01 +09003392 checkPendingIntentNotNull(operation);
Paul Jensen694f2b82015-06-17 14:15:39 -04003393 try {
3394 mService.pendingListenForNetwork(request.networkCapabilities, operation);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003395 } catch (RemoteException e) {
3396 throw e.rethrowFromSystemServer();
Hugo Benichicb883232017-05-11 13:16:17 +09003397 } catch (ServiceSpecificException e) {
3398 throw convertServiceException(e);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003399 }
Paul Jensen694f2b82015-06-17 14:15:39 -04003400 }
3401
3402 /**
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09003403 * Registers to receive notifications about changes in the system default network. The callbacks
3404 * will continue to be called until either the application exits or
3405 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Erik Klinea2d29402016-03-16 15:31:39 +09003406 *
3407 * @param networkCallback The {@link NetworkCallback} that the system will call as the
3408 * system default network changes.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003409 * The callback is invoked on the default internal Handler.
Erik Klinea2d29402016-03-16 15:31:39 +09003410 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003411 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Erik Klinea2d29402016-03-16 15:31:39 +09003412 public void registerDefaultNetworkCallback(NetworkCallback networkCallback) {
Hugo Benichi2583ef02017-02-02 17:02:36 +09003413 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
3414 }
3415
3416 /**
3417 * Registers to receive notifications about changes in the system default network. The callbacks
3418 * will continue to be called until either the application exits or
3419 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003420 *
3421 * @param networkCallback The {@link NetworkCallback} that the system will call as the
3422 * system default network changes.
3423 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
Hugo Benichi2583ef02017-02-02 17:02:36 +09003424 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003425 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Hugo Benichi2583ef02017-02-02 17:02:36 +09003426 public void registerDefaultNetworkCallback(NetworkCallback networkCallback, Handler handler) {
Erik Klinea2d29402016-03-16 15:31:39 +09003427 // This works because if the NetworkCapabilities are null,
3428 // ConnectivityService takes them from the default request.
3429 //
3430 // Since the capabilities are exactly the same as the default request's
3431 // capabilities, this request is guaranteed, at all times, to be
3432 // satisfied by the same network, if any, that satisfies the default
3433 // request, i.e., the system default network.
Hugo Benichie7678512017-05-09 15:19:01 +09003434 NetworkCapabilities nullCapabilities = null;
Hugo Benichi2583ef02017-02-02 17:02:36 +09003435 CallbackHandler cbHandler = new CallbackHandler(handler);
Hugo Benichie7678512017-05-09 15:19:01 +09003436 sendRequestForNetwork(nullCapabilities, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
Erik Klinea2d29402016-03-16 15:31:39 +09003437 }
3438
3439 /**
fengludb571472015-04-21 17:12:05 -07003440 * Requests bandwidth update for a given {@link Network} and returns whether the update request
3441 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
3442 * network connection for updated bandwidth information. The caller will be notified via
3443 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09003444 * method assumes that the caller has previously called
3445 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
3446 * changes.
fenglub15e72b2015-03-20 11:29:56 -07003447 *
fengluae519192015-04-27 14:28:04 -07003448 * @param network {@link Network} specifying which network you're interested.
fengludb571472015-04-21 17:12:05 -07003449 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
fenglub15e72b2015-03-20 11:29:56 -07003450 */
fengludb571472015-04-21 17:12:05 -07003451 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07003452 try {
fengludb571472015-04-21 17:12:05 -07003453 return mService.requestBandwidthUpdate(network);
fenglub15e72b2015-03-20 11:29:56 -07003454 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003455 throw e.rethrowFromSystemServer();
fenglub15e72b2015-03-20 11:29:56 -07003456 }
3457 }
3458
3459 /**
Hugo Benichidafed3d2017-03-06 09:17:06 +09003460 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
Lorenzo Colitti88bc0bb2016-04-13 22:00:02 +09003461 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
3462 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
3463 * If the given {@code NetworkCallback} had previously been used with
Lorenzo Colitti2ea89e52015-04-24 17:03:31 +09003464 * {@code #requestNetwork}, any networks that had been connected to only to satisfy that request
3465 * will be disconnected.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003466 *
Hugo Benichidafed3d2017-03-06 09:17:06 +09003467 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
3468 * triggering it as soon as this call returns.
3469 *
Robert Greenwalt6078b502014-06-11 16:05:07 -07003470 * @param networkCallback The {@link NetworkCallback} used when making the request.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003471 */
Robert Greenwalt6078b502014-06-11 16:05:07 -07003472 public void unregisterNetworkCallback(NetworkCallback networkCallback) {
Hugo Benichie7678512017-05-09 15:19:01 +09003473 checkCallbackNotNull(networkCallback);
Hugo Benichidafed3d2017-03-06 09:17:06 +09003474 final List<NetworkRequest> reqs = new ArrayList<>();
3475 // Find all requests associated to this callback and stop callback triggers immediately.
3476 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
3477 synchronized (sCallbacks) {
Hugo Benichi31c176d2017-06-17 13:14:12 +09003478 Preconditions.checkArgument(networkCallback.networkRequest != null,
3479 "NetworkCallback was not registered");
3480 Preconditions.checkArgument(networkCallback.networkRequest != ALREADY_UNREGISTERED,
3481 "NetworkCallback was already unregistered");
Hugo Benichidafed3d2017-03-06 09:17:06 +09003482 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
3483 if (e.getValue() == networkCallback) {
3484 reqs.add(e.getKey());
3485 }
3486 }
3487 // TODO: throw exception if callback was registered more than once (http://b/20701525).
3488 for (NetworkRequest r : reqs) {
3489 try {
3490 mService.releaseNetworkRequest(r);
3491 } catch (RemoteException e) {
3492 throw e.rethrowFromSystemServer();
3493 }
3494 // Only remove mapping if rpc was successful.
3495 sCallbacks.remove(r);
3496 }
Hugo Benichi31c176d2017-06-17 13:14:12 +09003497 networkCallback.networkRequest = ALREADY_UNREGISTERED;
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003498 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003499 }
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04003500
3501 /**
Paul Jensenf2c1cfe2015-06-30 14:29:18 -04003502 * Unregisters a callback previously registered via
3503 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
3504 *
3505 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
3506 * PendingIntent passed to
3507 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
3508 * Cannot be null.
3509 */
3510 public void unregisterNetworkCallback(PendingIntent operation) {
Hugo Benichie7678512017-05-09 15:19:01 +09003511 checkPendingIntentNotNull(operation);
Paul Jensenf2c1cfe2015-06-30 14:29:18 -04003512 releaseNetworkRequest(operation);
3513 }
3514
3515 /**
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003516 * Informs the system whether it should switch to {@code network} regardless of whether it is
3517 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
3518 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
3519 * the system default network regardless of any other network that's currently connected. If
3520 * {@code always} is true, then the choice is remembered, so that the next time the user
3521 * connects to this network, the system will switch to it.
3522 *
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003523 * @param network The network to accept.
3524 * @param accept Whether to accept the network even if unvalidated.
3525 * @param always Whether to remember this choice in the future.
3526 *
3527 * @hide
3528 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003529 @RequiresPermission(android.Manifest.permission.CONNECTIVITY_INTERNAL)
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003530 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
3531 try {
3532 mService.setAcceptUnvalidated(network, accept, always);
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003533 } catch (RemoteException e) {
3534 throw e.rethrowFromSystemServer();
3535 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003536 }
3537
3538 /**
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003539 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
3540 * only meaningful if the system is configured not to penalize such networks, e.g., if the
3541 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
3542 * NETWORK_AVOID_BAD_WIFI setting is unset}.
3543 *
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003544 * @param network The network to accept.
3545 *
3546 * @hide
3547 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003548 @RequiresPermission(android.Manifest.permission.CONNECTIVITY_INTERNAL)
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003549 public void setAvoidUnvalidated(Network network) {
3550 try {
3551 mService.setAvoidUnvalidated(network);
3552 } catch (RemoteException e) {
3553 throw e.rethrowFromSystemServer();
3554 }
3555 }
3556
3557 /**
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09003558 * Requests that the system open the captive portal app on the specified network.
3559 *
3560 * @param network The network to log into.
3561 *
3562 * @hide
3563 */
3564 @RequiresPermission(android.Manifest.permission.CONNECTIVITY_INTERNAL)
3565 public void startCaptivePortalApp(Network network) {
3566 try {
3567 mService.startCaptivePortalApp(network);
3568 } catch (RemoteException e) {
3569 throw e.rethrowFromSystemServer();
3570 }
3571 }
3572
3573 /**
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003574 * It is acceptable to briefly use multipath data to provide seamless connectivity for
3575 * time-sensitive user-facing operations when the system default network is temporarily
Lorenzo Colitti15fd4392017-04-28 00:56:30 +09003576 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
3577 * this method), and the operation should be infrequent to ensure that data usage is limited.
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003578 *
3579 * An example of such an operation might be a time-sensitive foreground activity, such as a
3580 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
3581 */
3582 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
3583
3584 /**
3585 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
3586 * a backup channel for traffic that is primarily going over another network.
3587 *
3588 * An example might be maintaining backup connections to peers or servers for the purpose of
3589 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
3590 * on backup paths should be negligible compared to the traffic on the main path.
3591 */
3592 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
3593
3594 /**
3595 * It is acceptable to use metered data to improve network latency and performance.
3596 */
3597 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
3598
3599 /**
3600 * Return value to use for unmetered networks. On such networks we currently set all the flags
3601 * to true.
3602 * @hide
3603 */
3604 public static final int MULTIPATH_PREFERENCE_UNMETERED =
3605 MULTIPATH_PREFERENCE_HANDOVER |
3606 MULTIPATH_PREFERENCE_RELIABILITY |
3607 MULTIPATH_PREFERENCE_PERFORMANCE;
3608
3609 /** @hide */
3610 @Retention(RetentionPolicy.SOURCE)
3611 @IntDef(flag = true, value = {
3612 MULTIPATH_PREFERENCE_HANDOVER,
3613 MULTIPATH_PREFERENCE_RELIABILITY,
3614 MULTIPATH_PREFERENCE_PERFORMANCE,
3615 })
3616 public @interface MultipathPreference {
3617 }
3618
3619 /**
3620 * Provides a hint to the calling application on whether it is desirable to use the
3621 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
3622 * for multipath data transfer on this network when it is not the system default network.
3623 * Applications desiring to use multipath network protocols should call this method before
3624 * each such operation.
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003625 *
3626 * @param network The network on which the application desires to use multipath data.
3627 * If {@code null}, this method will return the a preference that will generally
3628 * apply to metered networks.
3629 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
3630 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06003631 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003632 public @MultipathPreference int getMultipathPreference(Network network) {
3633 try {
3634 return mService.getMultipathPreference(network);
3635 } catch (RemoteException e) {
3636 throw e.rethrowFromSystemServer();
3637 }
3638 }
3639
3640 /**
Stuart Scott984dc852015-03-30 13:17:11 -07003641 * Resets all connectivity manager settings back to factory defaults.
3642 * @hide
3643 */
3644 public void factoryReset() {
Stuart Scott984dc852015-03-30 13:17:11 -07003645 try {
Stuart Scottf1fb3972015-04-02 18:00:02 -07003646 mService.factoryReset();
Stuart Scott984dc852015-03-30 13:17:11 -07003647 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003648 throw e.rethrowFromSystemServer();
Stuart Scott984dc852015-03-30 13:17:11 -07003649 }
3650 }
3651
3652 /**
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04003653 * Binds the current process to {@code network}. All Sockets created in the future
3654 * (and not explicitly bound via a bound SocketFactory from
3655 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
3656 * {@code network}. All host name resolutions will be limited to {@code network} as well.
3657 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
3658 * work and all host name resolutions will fail. This is by design so an application doesn't
3659 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
3660 * To clear binding pass {@code null} for {@code network}. Using individually bound
3661 * Sockets created by Network.getSocketFactory().createSocket() and
3662 * performing network-specific host name resolutions via
3663 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
Paul Jensen72db88e2015-03-10 10:54:12 -04003664 * {@code bindProcessToNetwork}.
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04003665 *
3666 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
3667 * the current binding.
3668 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
3669 */
Paul Jensen72db88e2015-03-10 10:54:12 -04003670 public boolean bindProcessToNetwork(Network network) {
3671 // Forcing callers to call thru non-static function ensures ConnectivityManager
3672 // instantiated.
3673 return setProcessDefaultNetwork(network);
3674 }
3675
3676 /**
3677 * Binds the current process to {@code network}. All Sockets created in the future
3678 * (and not explicitly bound via a bound SocketFactory from
3679 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
3680 * {@code network}. All host name resolutions will be limited to {@code network} as well.
3681 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
3682 * work and all host name resolutions will fail. This is by design so an application doesn't
3683 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
3684 * To clear binding pass {@code null} for {@code network}. Using individually bound
3685 * Sockets created by Network.getSocketFactory().createSocket() and
3686 * performing network-specific host name resolutions via
3687 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
3688 * {@code setProcessDefaultNetwork}.
3689 *
3690 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
3691 * the current binding.
3692 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
3693 * @deprecated This function can throw {@link IllegalStateException}. Use
3694 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
3695 * is a direct replacement.
3696 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07003697 @Deprecated
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04003698 public static boolean setProcessDefaultNetwork(Network network) {
Paul Jensenc91b5342014-08-27 12:38:45 -04003699 int netId = (network == null) ? NETID_UNSET : network.netId;
Paul Jensen72db88e2015-03-10 10:54:12 -04003700 if (netId == NetworkUtils.getBoundNetworkForProcess()) {
Paul Jensenc91b5342014-08-27 12:38:45 -04003701 return true;
3702 }
3703 if (NetworkUtils.bindProcessToNetwork(netId)) {
Paul Jensene0bef712014-12-10 15:12:18 -05003704 // Set HTTP proxy system properties to match network.
3705 // TODO: Deprecate this static method and replace it with a non-static version.
Lorenzo Colittiec4c5552015-04-22 11:52:48 +09003706 try {
3707 Proxy.setHttpProxySystemProperty(getInstance().getDefaultProxy());
3708 } catch (SecurityException e) {
3709 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
3710 Log.e(TAG, "Can't set proxy properties", e);
3711 }
Paul Jensenc91b5342014-08-27 12:38:45 -04003712 // Must flush DNS cache as new network may have different DNS resolutions.
3713 InetAddress.clearDnsCache();
3714 // Must flush socket pool as idle sockets will be bound to previous network and may
3715 // cause subsequent fetches to be performed on old network.
3716 NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
3717 return true;
3718 } else {
3719 return false;
3720 }
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04003721 }
3722
3723 /**
3724 * Returns the {@link Network} currently bound to this process via
Paul Jensen72db88e2015-03-10 10:54:12 -04003725 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04003726 *
3727 * @return {@code Network} to which this process is bound, or {@code null}.
3728 */
Paul Jensen72db88e2015-03-10 10:54:12 -04003729 public Network getBoundNetworkForProcess() {
3730 // Forcing callers to call thru non-static function ensures ConnectivityManager
3731 // instantiated.
3732 return getProcessDefaultNetwork();
3733 }
3734
3735 /**
3736 * Returns the {@link Network} currently bound to this process via
3737 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
3738 *
3739 * @return {@code Network} to which this process is bound, or {@code null}.
3740 * @deprecated Using this function can lead to other functions throwing
3741 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
3742 * {@code getBoundNetworkForProcess} is a direct replacement.
3743 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07003744 @Deprecated
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04003745 public static Network getProcessDefaultNetwork() {
Paul Jensen72db88e2015-03-10 10:54:12 -04003746 int netId = NetworkUtils.getBoundNetworkForProcess();
Paul Jensenbcc76d32014-07-11 08:17:29 -04003747 if (netId == NETID_UNSET) return null;
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04003748 return new Network(netId);
3749 }
3750
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09003751 private void unsupportedStartingFrom(int version) {
3752 if (Process.myUid() == Process.SYSTEM_UID) {
3753 // The getApplicationInfo() call we make below is not supported in system context, and
3754 // we want to allow the system to use these APIs anyway.
3755 return;
3756 }
3757
3758 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
3759 throw new UnsupportedOperationException(
3760 "This method is not supported in target SDK version " + version + " and above");
3761 }
3762 }
3763
3764 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
3765 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
Lifu Tang30f95a72016-01-07 23:20:38 -08003766 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09003767 // remove these exemptions. Note that this check is not secure, and apps can still access these
3768 // functions by accessing ConnectivityService directly. However, it should be clear that doing
3769 // so is unsupported and may break in the future. http://b/22728205
3770 private void checkLegacyRoutingApiAccess() {
3771 if (mContext.checkCallingOrSelfPermission("com.android.permission.INJECT_OMADM_SETTINGS")
3772 == PackageManager.PERMISSION_GRANTED) {
3773 return;
3774 }
3775
Dianne Hackborn692a2442015-07-31 10:35:34 -07003776 unsupportedStartingFrom(VERSION_CODES.M);
Lorenzo Colittiffc42b02015-07-29 11:41:21 +09003777 }
3778
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04003779 /**
3780 * Binds host resolutions performed by this process to {@code network}.
Paul Jensen72db88e2015-03-10 10:54:12 -04003781 * {@link #bindProcessToNetwork} takes precedence over this setting.
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04003782 *
3783 * @param network The {@link Network} to bind host resolutions from the current process to, or
3784 * {@code null} to clear the current binding.
3785 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
3786 * @hide
3787 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
3788 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -07003789 @Deprecated
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04003790 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
Paul Jensenbcc76d32014-07-11 08:17:29 -04003791 return NetworkUtils.bindProcessToNetworkForHostResolution(
3792 network == null ? NETID_UNSET : network.netId);
Paul Jensen6d3ff9e2014-05-29 10:12:39 -04003793 }
Felipe Leme1b103232016-01-22 09:44:57 -08003794
3795 /**
3796 * Device is not restricting metered network activity while application is running on
3797 * background.
3798 */
3799 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
3800
3801 /**
3802 * Device is restricting metered network activity while application is running on background,
3803 * but application is allowed to bypass it.
3804 * <p>
3805 * In this state, application should take action to mitigate metered network access.
3806 * For example, a music streaming application should switch to a low-bandwidth bitrate.
3807 */
3808 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
3809
3810 /**
3811 * Device is restricting metered network activity while application is running on background.
Felipe Leme9778f762016-01-27 14:46:39 -08003812 * <p>
Felipe Leme1b103232016-01-22 09:44:57 -08003813 * In this state, application should not try to use the network while running on background,
3814 * because it would be denied.
3815 */
3816 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
3817
Felipe Leme9778f762016-01-27 14:46:39 -08003818 /**
3819 * A change in the background metered network activity restriction has occurred.
3820 * <p>
3821 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
3822 * applies to them.
3823 * <p>
3824 * This is only sent to registered receivers, not manifest receivers.
3825 */
3826 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
3827 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
3828 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
3829
Felipe Lemeecfccea2016-01-25 11:48:04 -08003830 /** @hide */
3831 @Retention(RetentionPolicy.SOURCE)
Felipe Leme1b103232016-01-22 09:44:57 -08003832 @IntDef(flag = false, value = {
3833 RESTRICT_BACKGROUND_STATUS_DISABLED,
3834 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
3835 RESTRICT_BACKGROUND_STATUS_ENABLED,
3836 })
Felipe Leme1b103232016-01-22 09:44:57 -08003837 public @interface RestrictBackgroundStatus {
3838 }
3839
3840 private INetworkPolicyManager getNetworkPolicyManager() {
3841 synchronized (this) {
3842 if (mNPManager != null) {
3843 return mNPManager;
3844 }
3845 mNPManager = INetworkPolicyManager.Stub.asInterface(ServiceManager
3846 .getService(Context.NETWORK_POLICY_SERVICE));
3847 return mNPManager;
3848 }
3849 }
3850
3851 /**
3852 * Determines if the calling application is subject to metered network restrictions while
3853 * running on background.
Felipe Lemec9c7be52016-05-16 13:57:19 -07003854 *
3855 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
3856 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
3857 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
Felipe Leme1b103232016-01-22 09:44:57 -08003858 */
3859 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
3860 try {
3861 return getNetworkPolicyManager().getRestrictBackgroundByCaller();
3862 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07003863 throw e.rethrowFromSystemServer();
Felipe Leme1b103232016-01-22 09:44:57 -08003864 }
3865 }
Ricky Wai44dcbde2018-01-23 04:09:45 +00003866
3867 /**
3868 * The network watchlist is a list of domains and IP addresses that are associated with
Ricky Waia86d5d52018-03-20 14:20:54 +00003869 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
3870 * currently used by the system for validation purposes.
Ricky Wai44dcbde2018-01-23 04:09:45 +00003871 *
3872 * @return Hash of network watchlist config file. Null if config does not exist.
3873 */
3874 public byte[] getNetworkWatchlistConfigHash() {
3875 try {
3876 return mService.getNetworkWatchlistConfigHash();
3877 } catch (RemoteException e) {
3878 Log.e(TAG, "Unable to get watchlist config hash");
3879 throw e.rethrowFromSystemServer();
3880 }
3881 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003882}