• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /**
2  * Copyright (C) 2015 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5  * use this file except in compliance with the License. You may obtain a copy
6  * 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, WITHOUT
12  * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13  * License for the specific language governing permissions and limitations
14  * under the License.
15  */
16 
17 package android.app.usage;
18 
19 import static android.annotation.SystemApi.Client.MODULE_LIBRARIES;
20 import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR;
21 import static android.net.NetworkCapabilities.TRANSPORT_WIFI;
22 
23 import android.Manifest;
24 import android.annotation.CallbackExecutor;
25 import android.annotation.NonNull;
26 import android.annotation.Nullable;
27 import android.annotation.RequiresPermission;
28 import android.annotation.SystemApi;
29 import android.annotation.SystemService;
30 import android.annotation.WorkerThread;
31 import android.app.usage.NetworkStats.Bucket;
32 import android.compat.annotation.UnsupportedAppUsage;
33 import android.content.Context;
34 import android.net.ConnectivityManager;
35 import android.net.DataUsageRequest;
36 import android.net.INetworkStatsService;
37 import android.net.Network;
38 import android.net.NetworkStack;
39 import android.net.NetworkStateSnapshot;
40 import android.net.NetworkTemplate;
41 import android.net.UnderlyingNetworkInfo;
42 import android.net.netstats.IUsageCallback;
43 import android.net.netstats.NetworkStatsDataMigrationUtils;
44 import android.net.netstats.provider.INetworkStatsProviderCallback;
45 import android.net.netstats.provider.NetworkStatsProvider;
46 import android.os.Build;
47 import android.os.Handler;
48 import android.os.RemoteException;
49 import android.telephony.TelephonyManager;
50 import android.text.TextUtils;
51 import android.util.Log;
52 
53 import com.android.internal.annotations.VisibleForTesting;
54 import com.android.net.module.util.NetworkIdentityUtils;
55 
56 import java.util.List;
57 import java.util.Objects;
58 import java.util.concurrent.Executor;
59 
60 /**
61  * Provides access to network usage history and statistics. Usage data is collected in
62  * discrete bins of time called 'Buckets'. See {@link NetworkStats.Bucket} for details.
63  * <p />
64  * Queries can define a time interval in the form of start and end timestamps (Long.MIN_VALUE and
65  * Long.MAX_VALUE can be used to simulate open ended intervals). By default, apps can only obtain
66  * data about themselves. See the below note for special cases in which apps can obtain data about
67  * other applications.
68  * <h3>
69  * Summary queries
70  * </h3>
71  * {@link #querySummaryForDevice} <p />
72  * {@link #querySummaryForUser} <p />
73  * {@link #querySummary} <p />
74  * These queries aggregate network usage across the whole interval. Therefore there will be only one
75  * bucket for a particular key, state, metered and roaming combination. In case of the user-wide
76  * and device-wide summaries a single bucket containing the totalised network usage is returned.
77  * <h3>
78  * History queries
79  * </h3>
80  * {@link #queryDetailsForUid} <p />
81  * {@link #queryDetails} <p />
82  * These queries do not aggregate over time but do aggregate over state, metered and roaming.
83  * Therefore there can be multiple buckets for a particular key. However, all Buckets will have
84  * {@code state} {@link NetworkStats.Bucket#STATE_ALL},
85  * {@code defaultNetwork} {@link NetworkStats.Bucket#DEFAULT_NETWORK_ALL},
86  * {@code metered } {@link NetworkStats.Bucket#METERED_ALL},
87  * {@code roaming} {@link NetworkStats.Bucket#ROAMING_ALL}.
88  * <p />
89  * <b>NOTE:</b> Calling {@link #querySummaryForDevice} or accessing stats for apps other than the
90  * calling app requires the permission {@link android.Manifest.permission#PACKAGE_USAGE_STATS},
91  * which is a system-level permission and will not be granted to third-party apps. However,
92  * declaring the permission implies intention to use the API and the user of the device can grant
93  * permission through the Settings application.
94  * <p />
95  * Profile owner apps are automatically granted permission to query data on the profile they manage
96  * (that is, for any query except {@link #querySummaryForDevice}). Device owner apps and carrier-
97  * privileged apps likewise get access to usage data for all users on the device.
98  * <p />
99  * In addition to tethering usage, usage by removed users and apps, and usage by the system
100  * is also included in the results for callers with one of these higher levels of access.
101  * <p />
102  * <b>NOTE:</b> Prior to API level {@value android.os.Build.VERSION_CODES#N}, all calls to these APIs required
103  * the above permission, even to access an app's own data usage, and carrier-privileged apps were
104  * not included.
105  */
106 @SystemService(Context.NETWORK_STATS_SERVICE)
107 public class NetworkStatsManager {
108     private static final String TAG = "NetworkStatsManager";
109     private static final boolean DBG = false;
110 
111     /** @hide */
112     public static final int CALLBACK_LIMIT_REACHED = 0;
113     /** @hide */
114     public static final int CALLBACK_RELEASED = 1;
115 
116     /**
117      * Minimum data usage threshold for registering usage callbacks.
118      *
119      * Requests registered with a threshold lower than this will only be triggered once this minimum
120      * is reached.
121      * @hide
122      */
123     public static final long MIN_THRESHOLD_BYTES = 2 * 1_048_576L; // 2MiB
124 
125     private final Context mContext;
126     private final INetworkStatsService mService;
127 
128     /**
129      * @deprecated Use {@link NetworkStatsDataMigrationUtils#PREFIX_XT}
130      * instead.
131      * @hide
132      */
133     @Deprecated
134     public static final String PREFIX_DEV = "dev";
135 
136     /** @hide */
137     public static final int FLAG_POLL_ON_OPEN = 1 << 0;
138     /** @hide */
139     public static final int FLAG_POLL_FORCE = 1 << 1;
140     /** @hide */
141     public static final int FLAG_AUGMENT_WITH_SUBSCRIPTION_PLAN = 1 << 2;
142 
143     /**
144      * Virtual RAT type to represent 5G NSA (Non Stand Alone) mode, where the primary cell is
145      * still LTE and network allocates a secondary 5G cell so telephony reports RAT = LTE along
146      * with NR state as connected. This is a concept added by NetworkStats on top of the telephony
147      * constants for backward compatibility of metrics so this should not be overlapped with any of
148      * the {@code TelephonyManager.NETWORK_TYPE_*} constants.
149      *
150      * @hide
151      */
152     @SystemApi(client = MODULE_LIBRARIES)
153     public static final int NETWORK_TYPE_5G_NSA = -2;
154 
155     private int mFlags;
156 
157     /** @hide */
158     @VisibleForTesting
NetworkStatsManager(Context context, INetworkStatsService service)159     public NetworkStatsManager(Context context, INetworkStatsService service) {
160         mContext = context;
161         mService = service;
162         setPollOnOpen(true);
163         setAugmentWithSubscriptionPlan(true);
164     }
165 
166     /** @hide */
getBinder()167     public INetworkStatsService getBinder() {
168         return mService;
169     }
170 
171     /**
172      * Set poll on open flag to indicate the poll is needed before service gets statistics
173      * result. This is default enabled. However, for any non-privileged caller, the poll might
174      * be omitted in case of rate limiting.
175      *
176      * @param pollOnOpen true if poll is needed.
177      * @hide
178      */
179     // The system will ignore any non-default values for non-privileged
180     // processes, so processes that don't hold the appropriate permissions
181     // can make no use of this API.
182     @SystemApi(client = MODULE_LIBRARIES)
183     @RequiresPermission(anyOf = {
184             NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
185             android.Manifest.permission.NETWORK_STACK})
setPollOnOpen(boolean pollOnOpen)186     public void setPollOnOpen(boolean pollOnOpen) {
187         if (pollOnOpen) {
188             mFlags |= FLAG_POLL_ON_OPEN;
189         } else {
190             mFlags &= ~FLAG_POLL_ON_OPEN;
191         }
192     }
193 
194     /**
195      * Set poll force flag to indicate that calling any subsequent query method will force a stats
196      * poll.
197      * @hide
198      */
199     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
200     @SystemApi(client = MODULE_LIBRARIES)
setPollForce(boolean pollForce)201     public void setPollForce(boolean pollForce) {
202         if (pollForce) {
203             mFlags |= FLAG_POLL_FORCE;
204         } else {
205             mFlags &= ~FLAG_POLL_FORCE;
206         }
207     }
208 
209     /** @hide */
setAugmentWithSubscriptionPlan(boolean augmentWithSubscriptionPlan)210     public void setAugmentWithSubscriptionPlan(boolean augmentWithSubscriptionPlan) {
211         if (augmentWithSubscriptionPlan) {
212             mFlags |= FLAG_AUGMENT_WITH_SUBSCRIPTION_PLAN;
213         } else {
214             mFlags &= ~FLAG_AUGMENT_WITH_SUBSCRIPTION_PLAN;
215         }
216     }
217 
218     /**
219      * Query network usage statistics summaries.
220      *
221      * Result is summarised data usage for the whole
222      * device. Result is a single Bucket aggregated over time, state, uid, tag, metered, and
223      * roaming. This means the bucket's start and end timestamp will be the same as the
224      * 'startTime' and 'endTime' arguments. State is going to be
225      * {@link NetworkStats.Bucket#STATE_ALL}, uid {@link NetworkStats.Bucket#UID_ALL},
226      * tag {@link NetworkStats.Bucket#TAG_NONE},
227      * default network {@link NetworkStats.Bucket#DEFAULT_NETWORK_ALL},
228      * metered {@link NetworkStats.Bucket#METERED_ALL},
229      * and roaming {@link NetworkStats.Bucket#ROAMING_ALL}.
230      * This may take a long time, and apps should avoid calling this on their main thread.
231      *
232      * @param template Template used to match networks. See {@link NetworkTemplate}.
233      * @param startTime Start of period, in milliseconds since the Unix epoch, see
234      *            {@link java.lang.System#currentTimeMillis}.
235      * @param endTime End of period, in milliseconds since the Unix epoch, see
236      *            {@link java.lang.System#currentTimeMillis}.
237      * @return Bucket Summarised data usage.
238      *
239      * @hide
240      */
241     @NonNull
242     @WorkerThread
243     @SystemApi(client = MODULE_LIBRARIES)
querySummaryForDevice(@onNull NetworkTemplate template, long startTime, long endTime)244     public Bucket querySummaryForDevice(@NonNull NetworkTemplate template,
245             long startTime, long endTime) {
246         Objects.requireNonNull(template);
247         try {
248             NetworkStats stats =
249                     new NetworkStats(mContext, template, mFlags, startTime, endTime, mService);
250             Bucket bucket = stats.getDeviceSummaryForNetwork();
251             stats.close();
252             return bucket;
253         } catch (RemoteException e) {
254             e.rethrowFromSystemServer();
255         }
256         return null; // To make the compiler happy.
257     }
258 
259     /**
260      * Query network usage statistics summaries. Result is summarised data usage for the whole
261      * device. Result is a single Bucket aggregated over time, state, uid, tag, metered, and
262      * roaming. This means the bucket's start and end timestamp are going to be the same as the
263      * 'startTime' and 'endTime' parameters. State is going to be
264      * {@link NetworkStats.Bucket#STATE_ALL}, uid {@link NetworkStats.Bucket#UID_ALL},
265      * tag {@link NetworkStats.Bucket#TAG_NONE},
266      * default network {@link NetworkStats.Bucket#DEFAULT_NETWORK_ALL},
267      * metered {@link NetworkStats.Bucket#METERED_ALL},
268      * and roaming {@link NetworkStats.Bucket#ROAMING_ALL}.
269      * This may take a long time, and apps should avoid calling this on their main thread.
270      *
271      * @param networkType As defined in {@link ConnectivityManager}, e.g.
272      *            {@link ConnectivityManager#TYPE_MOBILE}, {@link ConnectivityManager#TYPE_WIFI}
273      *            etc.
274      * @param subscriberId If applicable, the subscriber id of the network interface.
275      *                     <p>Starting with API level 29, the {@code subscriberId} is guarded by
276      *                     additional restrictions. Calling apps that do not meet the new
277      *                     requirements to access the {@code subscriberId} can provide a {@code
278      *                     null} value when querying for the mobile network type to receive usage
279      *                     for all mobile networks. For additional details see {@link
280      *                     TelephonyManager#getSubscriberId()}.
281      *                     <p>Starting with API level 31, calling apps can provide a
282      *                     {@code subscriberId} with wifi network type to receive usage for
283      *                     wifi networks which is under the given subscription if applicable.
284      *                     Otherwise, pass {@code null} when querying all wifi networks.
285      * @param startTime Start of period. Defined in terms of "Unix time", see
286      *            {@link java.lang.System#currentTimeMillis}.
287      * @param endTime End of period. Defined in terms of "Unix time", see
288      *            {@link java.lang.System#currentTimeMillis}.
289      * @return Bucket object or null if permissions are insufficient or error happened during
290      *         statistics collection.
291      */
292     @WorkerThread
querySummaryForDevice(int networkType, @Nullable String subscriberId, long startTime, long endTime)293     public Bucket querySummaryForDevice(int networkType, @Nullable String subscriberId,
294             long startTime, long endTime) throws SecurityException, RemoteException {
295         NetworkTemplate template;
296         try {
297             template = createTemplate(networkType, subscriberId);
298         } catch (IllegalArgumentException e) {
299             if (DBG) Log.e(TAG, "Cannot create template", e);
300             return null;
301         }
302 
303         return querySummaryForDevice(template, startTime, endTime);
304     }
305 
306     /**
307      * Query network usage statistics summaries. Result is summarised data usage for all uids
308      * belonging to calling user. Result is a single Bucket aggregated over time, state and uid.
309      * This means the bucket's start and end timestamp are going to be the same as the 'startTime'
310      * and 'endTime' parameters. State is going to be {@link NetworkStats.Bucket#STATE_ALL},
311      * uid {@link NetworkStats.Bucket#UID_ALL}, tag {@link NetworkStats.Bucket#TAG_NONE},
312      * metered {@link NetworkStats.Bucket#METERED_ALL}, and roaming
313      * {@link NetworkStats.Bucket#ROAMING_ALL}.
314      * This may take a long time, and apps should avoid calling this on their main thread.
315      *
316      * @param networkType As defined in {@link ConnectivityManager}, e.g.
317      *            {@link ConnectivityManager#TYPE_MOBILE}, {@link ConnectivityManager#TYPE_WIFI}
318      *            etc.
319      * @param subscriberId If applicable, the subscriber id of the network interface.
320      *                     <p>Starting with API level 29, the {@code subscriberId} is guarded by
321      *                     additional restrictions. Calling apps that do not meet the new
322      *                     requirements to access the {@code subscriberId} can provide a {@code
323      *                     null} value when querying for the mobile network type to receive usage
324      *                     for all mobile networks. For additional details see {@link
325      *                     TelephonyManager#getSubscriberId()}.
326      *                     <p>Starting with API level 31, calling apps can provide a
327      *                     {@code subscriberId} with wifi network type to receive usage for
328      *                     wifi networks which is under the given subscription if applicable.
329      *                     Otherwise, pass {@code null} when querying all wifi networks.
330      * @param startTime Start of period. Defined in terms of "Unix time", see
331      *            {@link java.lang.System#currentTimeMillis}.
332      * @param endTime End of period. Defined in terms of "Unix time", see
333      *            {@link java.lang.System#currentTimeMillis}.
334      * @return Bucket object or null if permissions are insufficient or error happened during
335      *         statistics collection.
336      */
337     @WorkerThread
querySummaryForUser(int networkType, @Nullable String subscriberId, long startTime, long endTime)338     public Bucket querySummaryForUser(int networkType, @Nullable String subscriberId,
339             long startTime, long endTime) throws SecurityException, RemoteException {
340         NetworkTemplate template;
341         try {
342             template = createTemplate(networkType, subscriberId);
343         } catch (IllegalArgumentException e) {
344             if (DBG) Log.e(TAG, "Cannot create template", e);
345             return null;
346         }
347 
348         NetworkStats stats;
349         stats = new NetworkStats(mContext, template, mFlags, startTime, endTime, mService);
350         stats.startSummaryEnumeration();
351 
352         stats.close();
353         return stats.getSummaryAggregate();
354     }
355 
356     /**
357      * Query network usage statistics summaries. Result filtered to include only uids belonging to
358      * calling user. Result is aggregated over time, hence all buckets will have the same start and
359      * end timestamps. Not aggregated over state, uid, default network, metered, or roaming. This
360      * means buckets' start and end timestamps are going to be the same as the 'startTime' and
361      * 'endTime' parameters. State, uid, metered, and roaming are going to vary, and tag is going to
362      * be the same.
363      * This may take a long time, and apps should avoid calling this on their main thread.
364      *
365      * @param networkType As defined in {@link ConnectivityManager}, e.g.
366      *            {@link ConnectivityManager#TYPE_MOBILE}, {@link ConnectivityManager#TYPE_WIFI}
367      *            etc.
368      * @param subscriberId If applicable, the subscriber id of the network interface.
369      *                     <p>Starting with API level 29, the {@code subscriberId} is guarded by
370      *                     additional restrictions. Calling apps that do not meet the new
371      *                     requirements to access the {@code subscriberId} can provide a {@code
372      *                     null} value when querying for the mobile network type to receive usage
373      *                     for all mobile networks. For additional details see {@link
374      *                     TelephonyManager#getSubscriberId()}.
375      *                     <p>Starting with API level 31, calling apps can provide a
376      *                     {@code subscriberId} with wifi network type to receive usage for
377      *                     wifi networks which is under the given subscription if applicable.
378      *                     Otherwise, pass {@code null} when querying all wifi networks.
379      * @param startTime Start of period. Defined in terms of "Unix time", see
380      *            {@link java.lang.System#currentTimeMillis}.
381      * @param endTime End of period. Defined in terms of "Unix time", see
382      *            {@link java.lang.System#currentTimeMillis}.
383      * @return Statistics object or null if permissions are insufficient or error happened during
384      *         statistics collection.
385      */
386     @WorkerThread
querySummary(int networkType, @Nullable String subscriberId, long startTime, long endTime)387     public NetworkStats querySummary(int networkType, @Nullable String subscriberId, long startTime,
388             long endTime) throws SecurityException, RemoteException {
389         NetworkTemplate template;
390         try {
391             template = createTemplate(networkType, subscriberId);
392         } catch (IllegalArgumentException e) {
393             if (DBG) Log.e(TAG, "Cannot create template", e);
394             return null;
395         }
396 
397         return querySummary(template, startTime, endTime);
398     }
399 
400     /**
401      * Query network usage statistics summaries.
402      *
403      * The results will only include traffic made by UIDs belonging to the calling user profile.
404      * The results are aggregated over time, so that all buckets will have the same start and
405      * end timestamps as the passed arguments. Not aggregated over state, uid, default network,
406      * metered, or roaming.
407      * This may take a long time, and apps should avoid calling this on their main thread.
408      *
409      * @param template Template used to match networks. See {@link NetworkTemplate}.
410      * @param startTime Start of period, in milliseconds since the Unix epoch, see
411      *            {@link java.lang.System#currentTimeMillis}.
412      * @param endTime End of period, in milliseconds since the Unix epoch, see
413      *            {@link java.lang.System#currentTimeMillis}.
414      * @return Statistics which is described above.
415      * @hide
416      */
417     @NonNull
418     @SystemApi(client = MODULE_LIBRARIES)
419     @WorkerThread
querySummary(@onNull NetworkTemplate template, long startTime, long endTime)420     public NetworkStats querySummary(@NonNull NetworkTemplate template, long startTime,
421             long endTime) throws SecurityException {
422         Objects.requireNonNull(template);
423         try {
424             NetworkStats result =
425                     new NetworkStats(mContext, template, mFlags, startTime, endTime, mService);
426             result.startSummaryEnumeration();
427             return result;
428         } catch (RemoteException e) {
429             e.rethrowFromSystemServer();
430         }
431         return null; // To make the compiler happy.
432     }
433 
434     /**
435      * Query tagged network usage statistics summaries.
436      *
437      * The results will only include tagged traffic made by UIDs belonging to the calling user
438      * profile. The results are aggregated over time, so that all buckets will have the same
439      * start and end timestamps as the passed arguments. Not aggregated over state, uid,
440      * default network, metered, or roaming.
441      * This may take a long time, and apps should avoid calling this on their main thread.
442      *
443      * @param template Template used to match networks. See {@link NetworkTemplate}.
444      * @param startTime Start of period, in milliseconds since the Unix epoch, see
445      *            {@link System#currentTimeMillis}.
446      * @param endTime End of period, in milliseconds since the Unix epoch, see
447      *            {@link System#currentTimeMillis}.
448      * @return Statistics which is described above.
449      * @hide
450      */
451     @NonNull
452     @SystemApi(client = MODULE_LIBRARIES)
453     @WorkerThread
queryTaggedSummary(@onNull NetworkTemplate template, long startTime, long endTime)454     public NetworkStats queryTaggedSummary(@NonNull NetworkTemplate template, long startTime,
455             long endTime) throws SecurityException {
456         Objects.requireNonNull(template);
457         try {
458             NetworkStats result =
459                     new NetworkStats(mContext, template, mFlags, startTime, endTime, mService);
460             result.startTaggedSummaryEnumeration();
461             return result;
462         } catch (RemoteException e) {
463             e.rethrowFromSystemServer();
464         }
465         return null; // To make the compiler happy.
466     }
467 
468     /**
469      * Query usage statistics details for networks matching a given {@link NetworkTemplate}.
470      *
471      * Result is not aggregated over time. This means buckets' start and
472      * end timestamps will be between 'startTime' and 'endTime' parameters.
473      * <p>Only includes buckets whose entire time period is included between
474      * startTime and endTime. Doesn't interpolate or return partial buckets.
475      * Since bucket length is in the order of hours, this
476      * method cannot be used to measure data usage on a fine grained time scale.
477      * This may take a long time, and apps should avoid calling this on their main thread.
478      *
479      * @param template Template used to match networks. See {@link NetworkTemplate}.
480      * @param startTime Start of period, in milliseconds since the Unix epoch, see
481      *                  {@link java.lang.System#currentTimeMillis}.
482      * @param endTime End of period, in milliseconds since the Unix epoch, see
483      *                {@link java.lang.System#currentTimeMillis}.
484      * @return Statistics which is described above.
485      * @hide
486      */
487     @NonNull
488     @SystemApi(client = MODULE_LIBRARIES)
489     @WorkerThread
queryDetailsForDevice(@onNull NetworkTemplate template, long startTime, long endTime)490     public NetworkStats queryDetailsForDevice(@NonNull NetworkTemplate template,
491             long startTime, long endTime) {
492         Objects.requireNonNull(template);
493         try {
494             final NetworkStats result =
495                     new NetworkStats(mContext, template, mFlags, startTime, endTime, mService);
496             result.startHistoryDeviceEnumeration();
497             return result;
498         } catch (RemoteException e) {
499             e.rethrowFromSystemServer();
500         }
501 
502         return null; // To make the compiler happy.
503     }
504 
505     /**
506      * Query network usage statistics details for a given uid.
507      * This may take a long time, and apps should avoid calling this on their main thread.
508      *
509      * @see #queryDetailsForUidTagState(int, String, long, long, int, int, int)
510      */
511     @NonNull
512     @WorkerThread
queryDetailsForUid(int networkType, @Nullable String subscriberId, long startTime, long endTime, int uid)513     public NetworkStats queryDetailsForUid(int networkType, @Nullable String subscriberId,
514             long startTime, long endTime, int uid) throws SecurityException {
515         return queryDetailsForUidTagState(networkType, subscriberId, startTime, endTime, uid,
516             NetworkStats.Bucket.TAG_NONE, NetworkStats.Bucket.STATE_ALL);
517     }
518 
519     /** @hide */
520     @NonNull
queryDetailsForUid(@onNull NetworkTemplate template, long startTime, long endTime, int uid)521     public NetworkStats queryDetailsForUid(@NonNull NetworkTemplate template,
522             long startTime, long endTime, int uid) throws SecurityException {
523         return queryDetailsForUidTagState(template, startTime, endTime, uid,
524                 NetworkStats.Bucket.TAG_NONE, NetworkStats.Bucket.STATE_ALL);
525     }
526 
527     /**
528      * Query network usage statistics details for a given uid and tag.
529      *
530      * This may take a long time, and apps should avoid calling this on their main thread.
531      * Only usable for uids belonging to calling user. Result is not aggregated over time.
532      * This means buckets' start and end timestamps are going to be between 'startTime' and
533      * 'endTime' parameters. The uid is going to be the same as the 'uid' parameter, the tag
534      * the same as the 'tag' parameter, and the state the same as the 'state' parameter.
535      * defaultNetwork is going to be {@link NetworkStats.Bucket#DEFAULT_NETWORK_ALL},
536      * metered is going to be {@link NetworkStats.Bucket#METERED_ALL}, and
537      * roaming is going to be {@link NetworkStats.Bucket#ROAMING_ALL}.
538      * <p>Only includes buckets that atomically occur in the inclusive time range. Doesn't
539      * interpolate across partial buckets. Since bucket length is in the order of hours, this
540      * method cannot be used to measure data usage on a fine grained time scale.
541      * This may take a long time, and apps should avoid calling this on their main thread.
542      *
543      * @param networkType As defined in {@link ConnectivityManager}, e.g.
544      *            {@link ConnectivityManager#TYPE_MOBILE}, {@link ConnectivityManager#TYPE_WIFI}
545      *            etc.
546      * @param subscriberId If applicable, the subscriber id of the network interface.
547      *                     <p>Starting with API level 29, the {@code subscriberId} is guarded by
548      *                     additional restrictions. Calling apps that do not meet the new
549      *                     requirements to access the {@code subscriberId} can provide a {@code
550      *                     null} value when querying for the mobile network type to receive usage
551      *                     for all mobile networks. For additional details see {@link
552      *                     TelephonyManager#getSubscriberId()}.
553      *                     <p>Starting with API level 31, calling apps can provide a
554      *                     {@code subscriberId} with wifi network type to receive usage for
555      *                     wifi networks which is under the given subscription if applicable.
556      *                     Otherwise, pass {@code null} when querying all wifi networks.
557      * @param startTime Start of period. Defined in terms of "Unix time", see
558      *            {@link java.lang.System#currentTimeMillis}.
559      * @param endTime End of period. Defined in terms of "Unix time", see
560      *            {@link java.lang.System#currentTimeMillis}.
561      * @param uid UID of app
562      * @param tag TAG of interest. Use {@link NetworkStats.Bucket#TAG_NONE} for aggregated data
563      *            across all the tags.
564      * @return Statistics which is described above.
565      * @throws SecurityException if permissions are insufficient to read network statistics.
566      */
567     @NonNull
568     @WorkerThread
queryDetailsForUidTag(int networkType, @Nullable String subscriberId, long startTime, long endTime, int uid, int tag)569     public NetworkStats queryDetailsForUidTag(int networkType, @Nullable String subscriberId,
570             long startTime, long endTime, int uid, int tag) throws SecurityException {
571         return queryDetailsForUidTagState(networkType, subscriberId, startTime, endTime, uid,
572             tag, NetworkStats.Bucket.STATE_ALL);
573     }
574 
575     /**
576      * Query network usage statistics details for a given uid, tag, and state.
577      *
578      * Only usable for uids belonging to calling user. Result is not aggregated over time.
579      * This means buckets' start and end timestamps are going to be between 'startTime' and
580      * 'endTime' parameters. The uid is going to be the same as the 'uid' parameter, the tag
581      * the same as the 'tag' parameter, and the state the same as the 'state' parameter.
582      * defaultNetwork is going to be {@link NetworkStats.Bucket#DEFAULT_NETWORK_ALL},
583      * metered is going to be {@link NetworkStats.Bucket#METERED_ALL}, and
584      * roaming is going to be {@link NetworkStats.Bucket#ROAMING_ALL}.
585      * <p>Only includes buckets that atomically occur in the inclusive time range. Doesn't
586      * interpolate across partial buckets. Since bucket length is in the order of hours, this
587      * method cannot be used to measure data usage on a fine grained time scale.
588      * This may take a long time, and apps should avoid calling this on their main thread.
589      *
590      * @param networkType As defined in {@link ConnectivityManager}, e.g.
591      *            {@link ConnectivityManager#TYPE_MOBILE}, {@link ConnectivityManager#TYPE_WIFI}
592      *            etc.
593      * @param subscriberId If applicable, the subscriber id of the network interface.
594      *                     <p>Starting with API level 29, the {@code subscriberId} is guarded by
595      *                     additional restrictions. Calling apps that do not meet the new
596      *                     requirements to access the {@code subscriberId} can provide a {@code
597      *                     null} value when querying for the mobile network type to receive usage
598      *                     for all mobile networks. For additional details see {@link
599      *                     TelephonyManager#getSubscriberId()}.
600      *                     <p>Starting with API level 31, calling apps can provide a
601      *                     {@code subscriberId} with wifi network type to receive usage for
602      *                     wifi networks which is under the given subscription if applicable.
603      *                     Otherwise, pass {@code null} when querying all wifi networks.
604      * @param startTime Start of period. Defined in terms of "Unix time", see
605      *            {@link java.lang.System#currentTimeMillis}.
606      * @param endTime End of period. Defined in terms of "Unix time", see
607      *            {@link java.lang.System#currentTimeMillis}.
608      * @param uid UID of app
609      * @param tag TAG of interest. Use {@link NetworkStats.Bucket#TAG_NONE} for aggregated data
610      *            across all the tags.
611      * @param state state of interest. Use {@link NetworkStats.Bucket#STATE_ALL} to aggregate
612      *            traffic from all states.
613      * @return Statistics which is described above.
614      * @throws SecurityException if permissions are insufficient to read network statistics.
615      */
616     @NonNull
617     @WorkerThread
queryDetailsForUidTagState(int networkType, @Nullable String subscriberId, long startTime, long endTime, int uid, int tag, int state)618     public NetworkStats queryDetailsForUidTagState(int networkType, @Nullable String subscriberId,
619             long startTime, long endTime, int uid, int tag, int state) throws SecurityException {
620         NetworkTemplate template;
621         template = createTemplate(networkType, subscriberId);
622 
623         return queryDetailsForUidTagState(template, startTime, endTime, uid, tag, state);
624     }
625 
626     /**
627      * Query network usage statistics details for a given template, uid, tag, and state.
628      *
629      * Only usable for uids belonging to calling user. Result is not aggregated over time.
630      * This means buckets' start and end timestamps are going to be between 'startTime' and
631      * 'endTime' parameters. The uid is going to be the same as the 'uid' parameter, the tag
632      * the same as the 'tag' parameter, and the state the same as the 'state' parameter.
633      * defaultNetwork is going to be {@link NetworkStats.Bucket#DEFAULT_NETWORK_ALL},
634      * metered is going to be {@link NetworkStats.Bucket#METERED_ALL}, and
635      * roaming is going to be {@link NetworkStats.Bucket#ROAMING_ALL}.
636      * <p>Only includes buckets that atomically occur in the inclusive time range. Doesn't
637      * interpolate across partial buckets. Since bucket length is in the order of hours, this
638      * method cannot be used to measure data usage on a fine grained time scale.
639      * This may take a long time, and apps should avoid calling this on their main thread.
640      *
641      * @param template Template used to match networks. See {@link NetworkTemplate}.
642      * @param startTime Start of period, in milliseconds since the Unix epoch, see
643      *                  {@link java.lang.System#currentTimeMillis}.
644      * @param endTime End of period, in milliseconds since the Unix epoch, see
645      *                {@link java.lang.System#currentTimeMillis}.
646      * @param uid UID of app
647      * @param tag TAG of interest. Use {@link NetworkStats.Bucket#TAG_NONE} for aggregated data
648      *            across all the tags.
649      * @param state state of interest. Use {@link NetworkStats.Bucket#STATE_ALL} to aggregate
650      *            traffic from all states.
651      * @return Statistics which is described above.
652      * @hide
653      */
654     @NonNull
655     @SystemApi(client = MODULE_LIBRARIES)
656     @WorkerThread
queryDetailsForUidTagState(@onNull NetworkTemplate template, long startTime, long endTime, int uid, int tag, int state)657     public NetworkStats queryDetailsForUidTagState(@NonNull NetworkTemplate template,
658             long startTime, long endTime, int uid, int tag, int state) throws SecurityException {
659         Objects.requireNonNull(template);
660         try {
661             final NetworkStats result = new NetworkStats(
662                     mContext, template, mFlags, startTime, endTime, mService);
663             result.startHistoryUidEnumeration(uid, tag, state);
664             return result;
665         } catch (RemoteException e) {
666             Log.e(TAG, "Error while querying stats for uid=" + uid + " tag=" + tag
667                     + " state=" + state, e);
668             e.rethrowFromSystemServer();
669         }
670 
671         return null; // To make the compiler happy.
672     }
673 
674     /**
675      * Query network usage statistics details. Result filtered to include only uids belonging to
676      * calling user. Result is aggregated over state but not aggregated over time, uid, tag,
677      * metered, nor roaming. This means buckets' start and end timestamps are going to be between
678      * 'startTime' and 'endTime' parameters. State is going to be
679      * {@link NetworkStats.Bucket#STATE_ALL}, uid will vary,
680      * tag {@link NetworkStats.Bucket#TAG_NONE},
681      * default network is going to be {@link NetworkStats.Bucket#DEFAULT_NETWORK_ALL},
682      * metered is going to be {@link NetworkStats.Bucket#METERED_ALL},
683      * and roaming is going to be {@link NetworkStats.Bucket#ROAMING_ALL}.
684      * <p>Only includes buckets that atomically occur in the inclusive time range. Doesn't
685      * interpolate across partial buckets. Since bucket length is in the order of hours, this
686      * method cannot be used to measure data usage on a fine grained time scale.
687      * This may take a long time, and apps should avoid calling this on their main thread.
688      *
689      * @param networkType As defined in {@link ConnectivityManager}, e.g.
690      *            {@link ConnectivityManager#TYPE_MOBILE}, {@link ConnectivityManager#TYPE_WIFI}
691      *            etc.
692      * @param subscriberId If applicable, the subscriber id of the network interface.
693      *                     <p>Starting with API level 29, the {@code subscriberId} is guarded by
694      *                     additional restrictions. Calling apps that do not meet the new
695      *                     requirements to access the {@code subscriberId} can provide a {@code
696      *                     null} value when querying for the mobile network type to receive usage
697      *                     for all mobile networks. For additional details see {@link
698      *                     TelephonyManager#getSubscriberId()}.
699      *                     <p>Starting with API level 31, calling apps can provide a
700      *                     {@code subscriberId} with wifi network type to receive usage for
701      *                     wifi networks which is under the given subscription if applicable.
702      *                     Otherwise, pass {@code null} when querying all wifi networks.
703      * @param startTime Start of period. Defined in terms of "Unix time", see
704      *            {@link java.lang.System#currentTimeMillis}.
705      * @param endTime End of period. Defined in terms of "Unix time", see
706      *            {@link java.lang.System#currentTimeMillis}.
707      * @return Statistics object or null if permissions are insufficient or error happened during
708      *         statistics collection.
709      */
710     @WorkerThread
queryDetails(int networkType, @Nullable String subscriberId, long startTime, long endTime)711     public NetworkStats queryDetails(int networkType, @Nullable String subscriberId, long startTime,
712             long endTime) throws SecurityException, RemoteException {
713         NetworkTemplate template;
714         try {
715             template = createTemplate(networkType, subscriberId);
716         } catch (IllegalArgumentException e) {
717             if (DBG) Log.e(TAG, "Cannot create template", e);
718             return null;
719         }
720 
721         NetworkStats result;
722         result = new NetworkStats(mContext, template, mFlags, startTime, endTime, mService);
723         result.startUserUidEnumeration();
724         return result;
725     }
726 
727     /**
728      * Query realtime mobile network usage statistics.
729      *
730      * Return a snapshot of current UID network statistics, as it applies
731      * to the mobile radios of the device. The snapshot will include any
732      * tethering traffic, video calling data usage and count of
733      * network operations set by {@link TrafficStats#incrementOperationCount}
734      * made over a mobile radio.
735      * The snapshot will not include any statistics that cannot be seen by
736      * the kernel, e.g. statistics reported by {@link NetworkStatsProvider}s.
737      *
738      * @hide
739      */
740     @SystemApi(client = MODULE_LIBRARIES)
741     @RequiresPermission(anyOf = {
742             NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
743             android.Manifest.permission.NETWORK_STACK})
getMobileUidStats()744     @NonNull public android.net.NetworkStats getMobileUidStats() {
745         try {
746             return mService.getUidStatsForTransport(TRANSPORT_CELLULAR);
747         } catch (RemoteException e) {
748             if (DBG) Log.d(TAG, "Remote exception when get Mobile uid stats");
749             throw e.rethrowFromSystemServer();
750         }
751     }
752 
753     /**
754      * Query realtime Wi-Fi network usage statistics.
755      *
756      * Return a snapshot of current UID network statistics, as it applies
757      * to the Wi-Fi radios of the device. The snapshot will include any
758      * tethering traffic, video calling data usage and count of
759      * network operations set by {@link TrafficStats#incrementOperationCount}
760      * made over a Wi-Fi radio.
761      * The snapshot will not include any statistics that cannot be seen by
762      * the kernel, e.g. statistics reported by {@link NetworkStatsProvider}s.
763      *
764      * @hide
765      */
766     @SystemApi(client = MODULE_LIBRARIES)
767     @RequiresPermission(anyOf = {
768             NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
769             android.Manifest.permission.NETWORK_STACK})
getWifiUidStats()770     @NonNull public android.net.NetworkStats getWifiUidStats() {
771         try {
772             return mService.getUidStatsForTransport(TRANSPORT_WIFI);
773         } catch (RemoteException e) {
774             if (DBG) Log.d(TAG, "Remote exception when get WiFi uid stats");
775             throw e.rethrowFromSystemServer();
776         }
777     }
778 
779     /**
780      * Registers to receive notifications about data usage on specified networks.
781      *
782      * <p>The callbacks will continue to be called as long as the process is alive or
783      * {@link #unregisterUsageCallback} is called.
784      *
785      * @param template Template used to match networks. See {@link NetworkTemplate}.
786      * @param thresholdBytes Threshold in bytes to be notified on. Provided values lower than 2MiB
787      *                       will be clamped for callers except callers with the NETWORK_STACK
788      *                       permission.
789      * @param executor The executor on which callback will be invoked. The provided {@link Executor}
790      *                 must run callback sequentially, otherwise the order of callbacks cannot be
791      *                 guaranteed.
792      * @param callback The {@link UsageCallback} that the system will call when data usage
793      *                 has exceeded the specified threshold.
794      * @hide
795      */
796     @SystemApi(client = MODULE_LIBRARIES)
797     @RequiresPermission(anyOf = {
798             NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
799             android.Manifest.permission.NETWORK_STACK}, conditional = true)
registerUsageCallback(@onNull NetworkTemplate template, long thresholdBytes, @NonNull @CallbackExecutor Executor executor, @NonNull UsageCallback callback)800     public void registerUsageCallback(@NonNull NetworkTemplate template, long thresholdBytes,
801             @NonNull @CallbackExecutor Executor executor, @NonNull UsageCallback callback) {
802         Objects.requireNonNull(template, "NetworkTemplate cannot be null");
803         Objects.requireNonNull(callback, "UsageCallback cannot be null");
804         Objects.requireNonNull(executor, "Executor cannot be null");
805 
806         final DataUsageRequest request = new DataUsageRequest(DataUsageRequest.REQUEST_ID_UNSET,
807                 template, thresholdBytes);
808         try {
809             final UsageCallbackWrapper callbackWrapper =
810                     new UsageCallbackWrapper(executor, callback);
811             callback.request = mService.registerUsageCallback(
812                     mContext.getOpPackageName(), request, callbackWrapper);
813             if (DBG) Log.d(TAG, "registerUsageCallback returned " + callback.request);
814 
815             if (callback.request == null) {
816                 Log.e(TAG, "Request from callback is null; should not happen");
817             }
818         } catch (RemoteException e) {
819             if (DBG) Log.d(TAG, "Remote exception when registering callback");
820             throw e.rethrowFromSystemServer();
821         }
822     }
823 
824     /**
825      * Registers to receive notifications about data usage on specified networks.
826      *
827      * <p>The callbacks will continue to be called as long as the process is live or
828      * {@link #unregisterUsageCallback} is called.
829      *
830      * @param networkType Type of network to monitor. Either
831     {@link ConnectivityManager#TYPE_MOBILE} or {@link ConnectivityManager#TYPE_WIFI}.
832      * @param subscriberId If applicable, the subscriber id of the network interface.
833      *                     <p>Starting with API level 29, the {@code subscriberId} is guarded by
834      *                     additional restrictions. Calling apps that do not meet the new
835      *                     requirements to access the {@code subscriberId} can provide a {@code
836      *                     null} value when registering for the mobile network type to receive
837      *                     notifications for all mobile networks. For additional details see {@link
838      *                     TelephonyManager#getSubscriberId()}.
839      *                     <p>Starting with API level 31, calling apps can provide a
840      *                     {@code subscriberId} with wifi network type to receive usage for
841      *                     wifi networks which is under the given subscription if applicable.
842      *                     Otherwise, pass {@code null} when querying all wifi networks.
843      * @param thresholdBytes Threshold in bytes to be notified on.
844      * @param callback The {@link UsageCallback} that the system will call when data usage
845      *            has exceeded the specified threshold.
846      */
registerUsageCallback(int networkType, @Nullable String subscriberId, long thresholdBytes, @NonNull UsageCallback callback)847     public void registerUsageCallback(int networkType, @Nullable String subscriberId,
848             long thresholdBytes, @NonNull UsageCallback callback) {
849         registerUsageCallback(networkType, subscriberId, thresholdBytes, callback,
850                 null /* handler */);
851     }
852 
853     /**
854      * Registers to receive notifications about data usage on specified networks.
855      *
856      * <p>The callbacks will continue to be called as long as the process is live or
857      * {@link #unregisterUsageCallback} is called.
858      *
859      * @param networkType Type of network to monitor. Either
860                   {@link ConnectivityManager#TYPE_MOBILE} or {@link ConnectivityManager#TYPE_WIFI}.
861      * @param subscriberId If applicable, the subscriber id of the network interface.
862      *                     <p>Starting with API level 29, the {@code subscriberId} is guarded by
863      *                     additional restrictions. Calling apps that do not meet the new
864      *                     requirements to access the {@code subscriberId} can provide a {@code
865      *                     null} value when registering for the mobile network type to receive
866      *                     notifications for all mobile networks. For additional details see {@link
867      *                     TelephonyManager#getSubscriberId()}.
868      *                     <p>Starting with API level 31, calling apps can provide a
869      *                     {@code subscriberId} with wifi network type to receive usage for
870      *                     wifi networks which is under the given subscription if applicable.
871      *                     Otherwise, pass {@code null} when querying all wifi networks.
872      * @param thresholdBytes Threshold in bytes to be notified on.
873      * @param callback The {@link UsageCallback} that the system will call when data usage
874      *            has exceeded the specified threshold.
875      * @param handler to dispatch callback events through, otherwise if {@code null} it uses
876      *            the calling thread.
877      */
registerUsageCallback(int networkType, @Nullable String subscriberId, long thresholdBytes, @NonNull UsageCallback callback, @Nullable Handler handler)878     public void registerUsageCallback(int networkType, @Nullable String subscriberId,
879             long thresholdBytes, @NonNull UsageCallback callback, @Nullable Handler handler) {
880         NetworkTemplate template = createTemplate(networkType, subscriberId);
881         if (DBG) {
882             Log.d(TAG, "registerUsageCallback called with: {"
883                     + " networkType=" + networkType
884                     + " subscriberId=" + subscriberId
885                     + " thresholdBytes=" + thresholdBytes
886                     + " }");
887         }
888 
889         final Executor executor = handler == null ? r -> r.run() : r -> handler.post(r);
890 
891         registerUsageCallback(template, thresholdBytes, executor, callback);
892     }
893 
894     /**
895      * Unregisters callbacks on data usage.
896      *
897      * @param callback The {@link UsageCallback} used when registering.
898      */
unregisterUsageCallback(@onNull UsageCallback callback)899     public void unregisterUsageCallback(@NonNull UsageCallback callback) {
900         if (callback == null || callback.request == null
901                 || callback.request.requestId == DataUsageRequest.REQUEST_ID_UNSET) {
902             throw new IllegalArgumentException("Invalid UsageCallback");
903         }
904         try {
905             mService.unregisterUsageRequest(callback.request);
906         } catch (RemoteException e) {
907             if (DBG) Log.d(TAG, "Remote exception when unregistering callback");
908             throw e.rethrowFromSystemServer();
909         }
910     }
911 
912     /**
913      * Base class for usage callbacks. Should be extended by applications wanting notifications.
914      */
915     public static abstract class UsageCallback {
916         /**
917          * Called when data usage has reached the given threshold.
918          *
919          * Called by {@code NetworkStatsService} when the registered threshold is reached.
920          * If a caller implements {@link #onThresholdReached(NetworkTemplate)}, the system
921          * will not call {@link #onThresholdReached(int, String)}.
922          *
923          * @param template The {@link NetworkTemplate} that associated with this callback.
924          * @hide
925          */
926         @SystemApi(client = MODULE_LIBRARIES)
onThresholdReached(@onNull NetworkTemplate template)927         public void onThresholdReached(@NonNull NetworkTemplate template) {
928             // Backward compatibility for those who didn't override this function.
929             final int networkType = networkTypeForTemplate(template);
930             if (networkType != ConnectivityManager.TYPE_NONE) {
931                 final String subscriberId = template.getSubscriberIds().isEmpty() ? null
932                         : template.getSubscriberIds().iterator().next();
933                 onThresholdReached(networkType, subscriberId);
934             }
935         }
936 
937         /**
938          * Called when data usage has reached the given threshold.
939          */
onThresholdReached(int networkType, @Nullable String subscriberId)940         public abstract void onThresholdReached(int networkType, @Nullable String subscriberId);
941 
942         /**
943          * @hide used for internal bookkeeping
944          */
945         private DataUsageRequest request;
946 
947         /**
948          * Get network type from a template if feasible.
949          *
950          * @param template the target {@link NetworkTemplate}.
951          * @return legacy network type, only supports for the types which is already supported in
952          *         {@link #registerUsageCallback(int, String, long, UsageCallback, Handler)}.
953          *         {@link ConnectivityManager#TYPE_NONE} for other types.
954          */
networkTypeForTemplate(@onNull NetworkTemplate template)955         private static int networkTypeForTemplate(@NonNull NetworkTemplate template) {
956             switch (template.getMatchRule()) {
957                 case NetworkTemplate.MATCH_MOBILE:
958                     return ConnectivityManager.TYPE_MOBILE;
959                 case NetworkTemplate.MATCH_WIFI:
960                     return ConnectivityManager.TYPE_WIFI;
961                 default:
962                     return ConnectivityManager.TYPE_NONE;
963             }
964         }
965     }
966 
967     /**
968      * Registers a custom provider of {@link android.net.NetworkStats} to provide network statistics
969      * to the system. To unregister, invoke {@link #unregisterNetworkStatsProvider}.
970      * Note that no de-duplication of statistics between providers is performed, so each provider
971      * must only report network traffic that is not being reported by any other provider. Also note
972      * that the provider cannot be re-registered after unregistering.
973      *
974      * @param tag a human readable identifier of the custom network stats provider. This is only
975      *            used for debugging.
976      * @param provider the subclass of {@link NetworkStatsProvider} that needs to be
977      *                 registered to the system.
978      * @hide
979      */
980     @SystemApi
981     @RequiresPermission(anyOf = {
982             android.Manifest.permission.NETWORK_STATS_PROVIDER,
983             NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
registerNetworkStatsProvider( @onNull String tag, @NonNull NetworkStatsProvider provider)984     public void registerNetworkStatsProvider(
985             @NonNull String tag,
986             @NonNull NetworkStatsProvider provider) {
987         try {
988             if (provider.getProviderCallbackBinder() != null) {
989                 throw new IllegalArgumentException("provider is already registered");
990             }
991             final INetworkStatsProviderCallback cbBinder =
992                     mService.registerNetworkStatsProvider(tag, provider.getProviderBinder());
993             provider.setProviderCallbackBinder(cbBinder);
994         } catch (RemoteException e) {
995             e.rethrowAsRuntimeException();
996         }
997     }
998 
999     /**
1000      * Unregisters an instance of {@link NetworkStatsProvider}.
1001      *
1002      * @param provider the subclass of {@link NetworkStatsProvider} that needs to be
1003      *                 unregistered to the system.
1004      * @hide
1005      */
1006     @SystemApi
1007     @RequiresPermission(anyOf = {
1008             android.Manifest.permission.NETWORK_STATS_PROVIDER,
1009             NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
unregisterNetworkStatsProvider(@onNull NetworkStatsProvider provider)1010     public void unregisterNetworkStatsProvider(@NonNull NetworkStatsProvider provider) {
1011         try {
1012             provider.getProviderCallbackBinderOrThrow().unregister();
1013         } catch (RemoteException e) {
1014             e.rethrowAsRuntimeException();
1015         }
1016     }
1017 
createTemplate(int networkType, @Nullable String subscriberId)1018     private static NetworkTemplate createTemplate(int networkType, @Nullable String subscriberId) {
1019         final NetworkTemplate template;
1020         switch (networkType) {
1021             case ConnectivityManager.TYPE_MOBILE:
1022                 template = subscriberId == null
1023                         ? NetworkTemplate.buildTemplateMobileWildcard()
1024                         : NetworkTemplate.buildTemplateMobileAll(subscriberId);
1025                 break;
1026             case ConnectivityManager.TYPE_WIFI:
1027                 template = TextUtils.isEmpty(subscriberId)
1028                         ? NetworkTemplate.buildTemplateWifiWildcard()
1029                         : NetworkTemplate.buildTemplateWifi(NetworkTemplate.WIFI_NETWORKID_ALL,
1030                                 subscriberId);
1031                 break;
1032             default:
1033                 throw new IllegalArgumentException("Cannot create template for network type "
1034                         + networkType + ", subscriberId '"
1035                         + NetworkIdentityUtils.scrubSubscriberId(subscriberId) + "'.");
1036         }
1037         return template;
1038     }
1039 
1040     /**
1041      * Notify {@code NetworkStatsService} about network status changed.
1042      *
1043      * Notifies NetworkStatsService of network state changes for data usage accounting purposes.
1044      *
1045      * To avoid races that attribute data usage to wrong network, such as new network with
1046      * the same interface after SIM hot-swap, this function will not return until
1047      * {@code NetworkStatsService} finishes its work of retrieving traffic statistics from
1048      * all data sources.
1049      *
1050      * @param defaultNetworks the list of all networks that could be used by network traffic that
1051      *                        does not explicitly select a network.
1052      * @param networkStateSnapshots a list of {@link NetworkStateSnapshot}s, one for
1053      *                              each network that is currently connected.
1054      * @param activeIface the active (i.e., connected) default network interface for the calling
1055      *                    uid. Used to determine on which network future calls to
1056      *                    {@link android.net.TrafficStats#incrementOperationCount} applies to.
1057      * @param underlyingNetworkInfos the list of underlying network information for all
1058      *                               currently-connected VPNs.
1059      *
1060      * @hide
1061      */
1062     @SystemApi(client = MODULE_LIBRARIES)
1063     @RequiresPermission(anyOf = {
1064             NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1065             android.Manifest.permission.NETWORK_STACK})
notifyNetworkStatus( @onNull List<Network> defaultNetworks, @NonNull List<NetworkStateSnapshot> networkStateSnapshots, @Nullable String activeIface, @NonNull List<UnderlyingNetworkInfo> underlyingNetworkInfos)1066     public void notifyNetworkStatus(
1067             @NonNull List<Network> defaultNetworks,
1068             @NonNull List<NetworkStateSnapshot> networkStateSnapshots,
1069             @Nullable String activeIface,
1070             @NonNull List<UnderlyingNetworkInfo> underlyingNetworkInfos) {
1071         try {
1072             Objects.requireNonNull(defaultNetworks);
1073             Objects.requireNonNull(networkStateSnapshots);
1074             Objects.requireNonNull(underlyingNetworkInfos);
1075             mService.notifyNetworkStatus(defaultNetworks.toArray(new Network[0]),
1076                     networkStateSnapshots.toArray(new NetworkStateSnapshot[0]), activeIface,
1077                     underlyingNetworkInfos.toArray(new UnderlyingNetworkInfo[0]));
1078         } catch (RemoteException e) {
1079             throw e.rethrowFromSystemServer();
1080         }
1081     }
1082 
1083     private static class UsageCallbackWrapper extends IUsageCallback.Stub {
1084         // Null if unregistered.
1085         private volatile UsageCallback mCallback;
1086 
1087         private final Executor mExecutor;
1088 
UsageCallbackWrapper(@onNull Executor executor, @NonNull UsageCallback callback)1089         UsageCallbackWrapper(@NonNull Executor executor, @NonNull UsageCallback callback) {
1090             mCallback = callback;
1091             mExecutor = executor;
1092         }
1093 
1094         @Override
onThresholdReached(DataUsageRequest request)1095         public void onThresholdReached(DataUsageRequest request) {
1096             // Copy it to a local variable in case mCallback changed inside the if condition.
1097             final UsageCallback callback = mCallback;
1098             if (callback != null) {
1099                 mExecutor.execute(() -> callback.onThresholdReached(request.template));
1100             } else {
1101                 Log.e(TAG, "onThresholdReached with released callback for " + request);
1102             }
1103         }
1104 
1105         @Override
onCallbackReleased(DataUsageRequest request)1106         public void onCallbackReleased(DataUsageRequest request) {
1107             if (DBG) Log.d(TAG, "callback released for " + request);
1108             mCallback = null;
1109         }
1110     }
1111 
1112     /**
1113      * Mark given UID as being in foreground for stats purposes.
1114      *
1115      * @hide
1116      */
1117     @SystemApi(client = MODULE_LIBRARIES)
1118     @RequiresPermission(anyOf = {
1119             NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1120             android.Manifest.permission.NETWORK_STACK})
noteUidForeground(int uid, boolean uidForeground)1121     public void noteUidForeground(int uid, boolean uidForeground) {
1122         try {
1123             mService.noteUidForeground(uid, uidForeground);
1124         } catch (RemoteException e) {
1125             throw e.rethrowFromSystemServer();
1126         }
1127     }
1128 
1129     /**
1130      * Set default value of global alert bytes, the value will be clamped to [128kB, 2MB].
1131      *
1132      * @hide
1133      */
1134     @SystemApi(client = MODULE_LIBRARIES)
1135     @RequiresPermission(anyOf = {
1136             NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1137             Manifest.permission.NETWORK_STACK})
setDefaultGlobalAlert(long alertBytes)1138     public void setDefaultGlobalAlert(long alertBytes) {
1139         try {
1140             // TODO: Sync internal naming with the API surface.
1141             mService.advisePersistThreshold(alertBytes);
1142         } catch (RemoteException e) {
1143             throw e.rethrowFromSystemServer();
1144         }
1145     }
1146 
1147     /**
1148      * Force update of statistics.
1149      *
1150      * @hide
1151      */
1152     @SystemApi(client = MODULE_LIBRARIES)
1153     @RequiresPermission(anyOf = {
1154             NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1155             android.Manifest.permission.NETWORK_STACK})
forceUpdate()1156     public void forceUpdate() {
1157         try {
1158             mService.forceUpdate();
1159         } catch (RemoteException e) {
1160             throw e.rethrowFromSystemServer();
1161         }
1162     }
1163 
1164     /**
1165      * Set the warning and limit to all registered custom network stats providers.
1166      * Note that invocation of any interface will be sent to all providers.
1167      *
1168      * Asynchronicity notes : because traffic may be happening on the device at the same time, it
1169      * doesn't make sense to wait for the warning and limit to be set – a caller still wouldn't
1170      * know when exactly it was effective. All that can matter is that it's done quickly. Also,
1171      * this method can't fail, so there is no status to return. All providers will see the new
1172      * values soon.
1173      * As such, this method returns immediately and sends the warning and limit to all providers
1174      * as soon as possible through a one-way binder call.
1175      *
1176      * @hide
1177      */
1178     @SystemApi(client = MODULE_LIBRARIES)
1179     @RequiresPermission(anyOf = {
1180             NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1181             android.Manifest.permission.NETWORK_STACK})
setStatsProviderWarningAndLimitAsync(@onNull String iface, long warning, long limit)1182     public void setStatsProviderWarningAndLimitAsync(@NonNull String iface, long warning,
1183             long limit) {
1184         try {
1185             mService.setStatsProviderWarningAndLimitAsync(iface, warning, limit);
1186         } catch (RemoteException e) {
1187             throw e.rethrowFromSystemServer();
1188         }
1189     }
1190 
1191     /**
1192      * Get a RAT type representative of a group of RAT types for network statistics.
1193      *
1194      * Collapse the given Radio Access Technology (RAT) type into a bucket that
1195      * is representative of the original RAT type for network statistics. The
1196      * mapping mostly corresponds to {@code TelephonyManager#NETWORK_CLASS_BIT_MASK_*}
1197      * but with adaptations specific to the virtual types introduced by
1198      * networks stats.
1199      *
1200      * @param ratType An integer defined in {@code TelephonyManager#NETWORK_TYPE_*}.
1201      *
1202      * @hide
1203      */
1204     @SystemApi(client = MODULE_LIBRARIES)
getCollapsedRatType(int ratType)1205     public static int getCollapsedRatType(int ratType) {
1206         switch (ratType) {
1207             case TelephonyManager.NETWORK_TYPE_GPRS:
1208             case TelephonyManager.NETWORK_TYPE_GSM:
1209             case TelephonyManager.NETWORK_TYPE_EDGE:
1210             case TelephonyManager.NETWORK_TYPE_IDEN:
1211             case TelephonyManager.NETWORK_TYPE_CDMA:
1212             case TelephonyManager.NETWORK_TYPE_1xRTT:
1213                 return TelephonyManager.NETWORK_TYPE_GSM;
1214             case TelephonyManager.NETWORK_TYPE_EVDO_0:
1215             case TelephonyManager.NETWORK_TYPE_EVDO_A:
1216             case TelephonyManager.NETWORK_TYPE_EVDO_B:
1217             case TelephonyManager.NETWORK_TYPE_EHRPD:
1218             case TelephonyManager.NETWORK_TYPE_UMTS:
1219             case TelephonyManager.NETWORK_TYPE_HSDPA:
1220             case TelephonyManager.NETWORK_TYPE_HSUPA:
1221             case TelephonyManager.NETWORK_TYPE_HSPA:
1222             case TelephonyManager.NETWORK_TYPE_HSPAP:
1223             case TelephonyManager.NETWORK_TYPE_TD_SCDMA:
1224                 return TelephonyManager.NETWORK_TYPE_UMTS;
1225             case TelephonyManager.NETWORK_TYPE_LTE:
1226             case TelephonyManager.NETWORK_TYPE_IWLAN:
1227                 return TelephonyManager.NETWORK_TYPE_LTE;
1228             case TelephonyManager.NETWORK_TYPE_NR:
1229                 return TelephonyManager.NETWORK_TYPE_NR;
1230             // Virtual RAT type for 5G NSA mode, see
1231             // {@link NetworkStatsManager#NETWORK_TYPE_5G_NSA}.
1232             case NetworkStatsManager.NETWORK_TYPE_5G_NSA:
1233                 return NetworkStatsManager.NETWORK_TYPE_5G_NSA;
1234             default:
1235                 return TelephonyManager.NETWORK_TYPE_UNKNOWN;
1236         }
1237     }
1238 }
1239