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