• 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 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      * @see #queryDetailsForUidTagState(int, String, long, long, int, int, int)
514      */
515     @NonNull
516     @WorkerThread
queryDetailsForUid(int networkType, @Nullable String subscriberId, long startTime, long endTime, int uid)517     public NetworkStats queryDetailsForUid(int networkType, @Nullable String subscriberId,
518             long startTime, long endTime, int uid) throws SecurityException {
519         return queryDetailsForUidTagState(networkType, subscriberId, startTime, endTime, uid,
520             NetworkStats.Bucket.TAG_NONE, NetworkStats.Bucket.STATE_ALL);
521     }
522 
523     /** @hide */
524     @NonNull
queryDetailsForUid(@onNull NetworkTemplate template, long startTime, long endTime, int uid)525     public NetworkStats queryDetailsForUid(@NonNull NetworkTemplate template,
526             long startTime, long endTime, int uid) throws SecurityException {
527         return queryDetailsForUidTagState(template, startTime, endTime, uid,
528                 NetworkStats.Bucket.TAG_NONE, NetworkStats.Bucket.STATE_ALL);
529     }
530 
531     /**
532      * Query network usage statistics details for a given uid and tag.
533      *
534      * This may take a long time, and apps should avoid calling this on their main thread.
535      * Only usable for uids belonging to calling user. Result is not aggregated over time.
536      * This means buckets' start and end timestamps are going to be between 'startTime' and
537      * 'endTime' parameters. The uid is going to be the same as the 'uid' parameter, the tag
538      * the same as the 'tag' parameter, and the state the same as the 'state' parameter.
539      * defaultNetwork is going to be {@link NetworkStats.Bucket#DEFAULT_NETWORK_ALL},
540      * metered is going to be {@link NetworkStats.Bucket#METERED_ALL}, and
541      * roaming is going to be {@link NetworkStats.Bucket#ROAMING_ALL}.
542      * <p>Only includes buckets that atomically occur in the inclusive time range. Doesn't
543      * interpolate across partial buckets. Since bucket length is in the order of hours, this
544      * method cannot be used to measure data usage on a fine grained time scale.
545      * This may take a long time, and apps should avoid calling this on their main thread.
546      *
547      * @param networkType As defined in {@link ConnectivityManager}, e.g.
548      *            {@link ConnectivityManager#TYPE_MOBILE}, {@link ConnectivityManager#TYPE_WIFI}
549      *            etc.
550      * @param subscriberId If applicable, the subscriber id of the network interface.
551      *                     <p>Starting with API level 29, the {@code subscriberId} is guarded by
552      *                     additional restrictions. Calling apps that do not meet the new
553      *                     requirements to access the {@code subscriberId} can provide a {@code
554      *                     null} value when querying for the mobile network type to receive usage
555      *                     for all mobile networks. For additional details see {@link
556      *                     TelephonyManager#getSubscriberId()}.
557      *                     <p>Starting with API level 31, calling apps can provide a
558      *                     {@code subscriberId} with wifi network type to receive usage for
559      *                     wifi networks which is under the given subscription if applicable.
560      *                     Otherwise, pass {@code null} when querying all wifi networks.
561      * @param startTime Start of period. Defined in terms of "Unix time", see
562      *            {@link java.lang.System#currentTimeMillis}.
563      * @param endTime End of period. Defined in terms of "Unix time", see
564      *            {@link java.lang.System#currentTimeMillis}.
565      * @param uid UID of app
566      * @param tag TAG of interest. Use {@link NetworkStats.Bucket#TAG_NONE} for aggregated data
567      *            across all the tags.
568      * @return Statistics which is described above.
569      * @throws SecurityException if permissions are insufficient to read network statistics.
570      */
571     @NonNull
572     @WorkerThread
queryDetailsForUidTag(int networkType, @Nullable String subscriberId, long startTime, long endTime, int uid, int tag)573     public NetworkStats queryDetailsForUidTag(int networkType, @Nullable String subscriberId,
574             long startTime, long endTime, int uid, int tag) throws SecurityException {
575         return queryDetailsForUidTagState(networkType, subscriberId, startTime, endTime, uid,
576             tag, NetworkStats.Bucket.STATE_ALL);
577     }
578 
579     /**
580      * Query network usage statistics details for a given uid, tag, and state.
581      *
582      * Only usable for uids belonging to calling user. Result is not aggregated over time.
583      * This means buckets' start and end timestamps are going to be between 'startTime' and
584      * 'endTime' parameters. The uid is going to be the same as the 'uid' parameter, the tag
585      * the same as the 'tag' parameter, and the state the same as the 'state' parameter.
586      * defaultNetwork is going to be {@link NetworkStats.Bucket#DEFAULT_NETWORK_ALL},
587      * metered is going to be {@link NetworkStats.Bucket#METERED_ALL}, and
588      * roaming is going to be {@link NetworkStats.Bucket#ROAMING_ALL}.
589      * <p>Only includes buckets that atomically occur in the inclusive time range. Doesn't
590      * interpolate across partial buckets. Since bucket length is in the order of hours, this
591      * method cannot be used to measure data usage on a fine grained time scale.
592      * This may take a long time, and apps should avoid calling this on their main thread.
593      *
594      * @param networkType As defined in {@link ConnectivityManager}, e.g.
595      *            {@link ConnectivityManager#TYPE_MOBILE}, {@link ConnectivityManager#TYPE_WIFI}
596      *            etc.
597      * @param subscriberId If applicable, the subscriber id of the network interface.
598      *                     <p>Starting with API level 29, the {@code subscriberId} is guarded by
599      *                     additional restrictions. Calling apps that do not meet the new
600      *                     requirements to access the {@code subscriberId} can provide a {@code
601      *                     null} value when querying for the mobile network type to receive usage
602      *                     for all mobile networks. For additional details see {@link
603      *                     TelephonyManager#getSubscriberId()}.
604      *                     <p>Starting with API level 31, calling apps can provide a
605      *                     {@code subscriberId} with wifi network type to receive usage for
606      *                     wifi networks which is under the given subscription if applicable.
607      *                     Otherwise, pass {@code null} when querying all wifi networks.
608      * @param startTime Start of period. Defined in terms of "Unix time", see
609      *            {@link java.lang.System#currentTimeMillis}.
610      * @param endTime End of period. Defined in terms of "Unix time", see
611      *            {@link java.lang.System#currentTimeMillis}.
612      * @param uid UID of app
613      * @param tag TAG of interest. Use {@link NetworkStats.Bucket#TAG_NONE} for aggregated data
614      *            across all the tags.
615      * @param state state of interest. Use {@link NetworkStats.Bucket#STATE_ALL} to aggregate
616      *            traffic from all states.
617      * @return Statistics which is described above.
618      * @throws SecurityException if permissions are insufficient to read network statistics.
619      */
620     @NonNull
621     @WorkerThread
queryDetailsForUidTagState(int networkType, @Nullable String subscriberId, long startTime, long endTime, int uid, int tag, int state)622     public NetworkStats queryDetailsForUidTagState(int networkType, @Nullable String subscriberId,
623             long startTime, long endTime, int uid, int tag, int state) throws SecurityException {
624         NetworkTemplate template;
625         template = createTemplate(networkType, subscriberId);
626 
627         return queryDetailsForUidTagState(template, startTime, endTime, uid, tag, state);
628     }
629 
630     /**
631      * Query network usage statistics details for a given template, uid, tag, and state.
632      *
633      * Only usable for uids belonging to calling user. Result is not aggregated over time.
634      * This means buckets' start and end timestamps are going to be between 'startTime' and
635      * 'endTime' parameters. The uid is going to be the same as the 'uid' parameter, the tag
636      * the same as the 'tag' parameter, and the state the same as the 'state' parameter.
637      * defaultNetwork is going to be {@link NetworkStats.Bucket#DEFAULT_NETWORK_ALL},
638      * metered is going to be {@link NetworkStats.Bucket#METERED_ALL}, and
639      * roaming is going to be {@link NetworkStats.Bucket#ROAMING_ALL}.
640      * <p>Only includes buckets that atomically occur in the inclusive time range. Doesn't
641      * interpolate across partial buckets. Since bucket length is in the order of hours, this
642      * method cannot be used to measure data usage on a fine grained time scale.
643      * This may take a long time, and apps should avoid calling this on their main thread.
644      *
645      * @param template Template used to match networks. See {@link NetworkTemplate}.
646      * @param startTime Start of period, in milliseconds since the Unix epoch, see
647      *                  {@link java.lang.System#currentTimeMillis}.
648      * @param endTime End of period, in milliseconds since the Unix epoch, see
649      *                {@link java.lang.System#currentTimeMillis}.
650      * @param uid UID of app
651      * @param tag TAG of interest. Use {@link NetworkStats.Bucket#TAG_NONE} for aggregated data
652      *            across all the tags.
653      * @param state state of interest. Use {@link NetworkStats.Bucket#STATE_ALL} to aggregate
654      *            traffic from all states.
655      * @return Statistics which is described above.
656      * @hide
657      */
658     @NonNull
659     @SystemApi(client = MODULE_LIBRARIES)
660     @WorkerThread
queryDetailsForUidTagState(@onNull NetworkTemplate template, long startTime, long endTime, int uid, int tag, int state)661     public NetworkStats queryDetailsForUidTagState(@NonNull NetworkTemplate template,
662             long startTime, long endTime, int uid, int tag, int state) throws SecurityException {
663         Objects.requireNonNull(template);
664         try {
665             final NetworkStats result = new NetworkStats(
666                     mContext, template, mFlags, startTime, endTime, mService);
667             result.startHistoryUidEnumeration(uid, tag, state);
668             return result;
669         } catch (RemoteException e) {
670             Log.e(TAG, "Error while querying stats for uid=" + uid + " tag=" + tag
671                     + " state=" + state, e);
672             e.rethrowFromSystemServer();
673         }
674 
675         return null; // To make the compiler happy.
676     }
677 
678     /**
679      * Query network usage statistics details. Result filtered to include only uids belonging to
680      * calling user. Result is aggregated over state but not aggregated over time, uid, tag,
681      * metered, nor roaming. This means buckets' start and end timestamps are going to be between
682      * 'startTime' and 'endTime' parameters. State is going to be
683      * {@link NetworkStats.Bucket#STATE_ALL}, uid will vary,
684      * tag {@link NetworkStats.Bucket#TAG_NONE},
685      * default network is going to be {@link NetworkStats.Bucket#DEFAULT_NETWORK_ALL},
686      * metered is going to be {@link NetworkStats.Bucket#METERED_ALL},
687      * and roaming is going to be {@link NetworkStats.Bucket#ROAMING_ALL}.
688      * <p>Only includes buckets that atomically occur in the inclusive time range. Doesn't
689      * interpolate across partial buckets. Since bucket length is in the order of hours, this
690      * method cannot be used to measure data usage on a fine grained time scale.
691      * This may take a long time, and apps should avoid calling this on their main thread.
692      *
693      * @param networkType As defined in {@link ConnectivityManager}, e.g.
694      *            {@link ConnectivityManager#TYPE_MOBILE}, {@link ConnectivityManager#TYPE_WIFI}
695      *            etc.
696      * @param subscriberId If applicable, the subscriber id of the network interface.
697      *                     <p>Starting with API level 29, the {@code subscriberId} is guarded by
698      *                     additional restrictions. Calling apps that do not meet the new
699      *                     requirements to access the {@code subscriberId} can provide a {@code
700      *                     null} value when querying for the mobile network type to receive usage
701      *                     for all mobile networks. For additional details see {@link
702      *                     TelephonyManager#getSubscriberId()}.
703      *                     <p>Starting with API level 31, calling apps can provide a
704      *                     {@code subscriberId} with wifi network type to receive usage for
705      *                     wifi networks which is under the given subscription if applicable.
706      *                     Otherwise, pass {@code null} when querying all wifi networks.
707      * @param startTime Start of period. Defined in terms of "Unix time", see
708      *            {@link java.lang.System#currentTimeMillis}.
709      * @param endTime End of period. Defined in terms of "Unix time", see
710      *            {@link java.lang.System#currentTimeMillis}.
711      * @return Statistics object or null if permissions are insufficient or error happened during
712      *         statistics collection.
713      */
714     @WorkerThread
queryDetails(int networkType, @Nullable String subscriberId, long startTime, long endTime)715     public NetworkStats queryDetails(int networkType, @Nullable String subscriberId, long startTime,
716             long endTime) throws SecurityException, RemoteException {
717         NetworkTemplate template;
718         try {
719             template = createTemplate(networkType, subscriberId);
720         } catch (IllegalArgumentException e) {
721             if (DBG) Log.e(TAG, "Cannot create template", e);
722             return null;
723         }
724 
725         NetworkStats result;
726         result = new NetworkStats(mContext, template, mFlags, startTime, endTime, mService);
727         result.startUserUidEnumeration();
728         return result;
729     }
730 
731     /**
732      * Query realtime mobile network usage statistics.
733      *
734      * Return a snapshot of current UID network statistics, as it applies
735      * to the mobile radios of the device. The snapshot will include any
736      * tethering traffic, video calling data usage and count of
737      * network operations set by {@link TrafficStats#incrementOperationCount}
738      * made over a mobile radio.
739      * The snapshot will not include any statistics that cannot be seen by
740      * the kernel, e.g. statistics reported by {@link NetworkStatsProvider}s.
741      *
742      * @hide
743      */
744     @SystemApi(client = MODULE_LIBRARIES)
745     @RequiresPermission(anyOf = {
746             NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
747             android.Manifest.permission.NETWORK_STACK})
getMobileUidStats()748     @NonNull public android.net.NetworkStats getMobileUidStats() {
749         try {
750             return mService.getUidStatsForTransport(TRANSPORT_CELLULAR);
751         } catch (RemoteException e) {
752             if (DBG) Log.d(TAG, "Remote exception when get Mobile uid stats");
753             throw e.rethrowFromSystemServer();
754         }
755     }
756 
757     /**
758      * Query realtime Wi-Fi network usage statistics.
759      *
760      * Return a snapshot of current UID network statistics, as it applies
761      * to the Wi-Fi radios of the device. The snapshot will include any
762      * tethering traffic, video calling data usage and count of
763      * network operations set by {@link TrafficStats#incrementOperationCount}
764      * made over a Wi-Fi radio.
765      * The snapshot will not include any statistics that cannot be seen by
766      * the kernel, e.g. statistics reported by {@link NetworkStatsProvider}s.
767      *
768      * @hide
769      */
770     @SystemApi(client = MODULE_LIBRARIES)
771     @RequiresPermission(anyOf = {
772             NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
773             android.Manifest.permission.NETWORK_STACK})
getWifiUidStats()774     @NonNull public android.net.NetworkStats getWifiUidStats() {
775         try {
776             return mService.getUidStatsForTransport(TRANSPORT_WIFI);
777         } catch (RemoteException e) {
778             if (DBG) Log.d(TAG, "Remote exception when get WiFi uid stats");
779             throw e.rethrowFromSystemServer();
780         }
781     }
782 
783     /**
784      * Registers to receive notifications about data usage on specified networks.
785      *
786      * <p>The callbacks will continue to be called as long as the process is alive or
787      * {@link #unregisterUsageCallback} is called.
788      *
789      * @param template Template used to match networks. See {@link NetworkTemplate}.
790      * @param thresholdBytes Threshold in bytes to be notified on. Provided values lower than 2MiB
791      *                       will be clamped for callers except callers with the NETWORK_STACK
792      *                       permission.
793      * @param executor The executor on which callback will be invoked. The provided {@link Executor}
794      *                 must run callback sequentially, otherwise the order of callbacks cannot be
795      *                 guaranteed.
796      * @param callback The {@link UsageCallback} that the system will call when data usage
797      *                 has exceeded the specified threshold.
798      * @hide
799      */
800     @SystemApi(client = MODULE_LIBRARIES)
801     @RequiresPermission(anyOf = {
802             NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
803             android.Manifest.permission.NETWORK_STACK}, conditional = true)
registerUsageCallback(@onNull NetworkTemplate template, long thresholdBytes, @NonNull @CallbackExecutor Executor executor, @NonNull UsageCallback callback)804     public void registerUsageCallback(@NonNull NetworkTemplate template, long thresholdBytes,
805             @NonNull @CallbackExecutor Executor executor, @NonNull UsageCallback callback) {
806         Objects.requireNonNull(template, "NetworkTemplate cannot be null");
807         Objects.requireNonNull(callback, "UsageCallback cannot be null");
808         Objects.requireNonNull(executor, "Executor cannot be null");
809 
810         final DataUsageRequest request = new DataUsageRequest(DataUsageRequest.REQUEST_ID_UNSET,
811                 template, thresholdBytes);
812         try {
813             final UsageCallbackWrapper callbackWrapper =
814                     new UsageCallbackWrapper(executor, callback);
815             callback.request = mService.registerUsageCallback(
816                     mContext.getOpPackageName(), request, callbackWrapper);
817             if (DBG) Log.d(TAG, "registerUsageCallback returned " + callback.request);
818 
819             if (callback.request == null) {
820                 Log.e(TAG, "Request from callback is null; should not happen");
821             }
822         } catch (RemoteException e) {
823             if (DBG) Log.d(TAG, "Remote exception when registering callback");
824             throw e.rethrowFromSystemServer();
825         }
826     }
827 
828     /**
829      * Registers to receive notifications about data usage on specified networks.
830      *
831      * <p>The callbacks will continue to be called as long as the process is live or
832      * {@link #unregisterUsageCallback} is called.
833      *
834      * @param networkType Type of network to monitor. Either
835     {@link ConnectivityManager#TYPE_MOBILE} or {@link ConnectivityManager#TYPE_WIFI}.
836      * @param subscriberId If applicable, the subscriber id of the network interface.
837      *                     <p>Starting with API level 29, the {@code subscriberId} is guarded by
838      *                     additional restrictions. Calling apps that do not meet the new
839      *                     requirements to access the {@code subscriberId} can provide a {@code
840      *                     null} value when registering for the mobile network type to receive
841      *                     notifications for all mobile networks. For additional details see {@link
842      *                     TelephonyManager#getSubscriberId()}.
843      *                     <p>Starting with API level 31, calling apps can provide a
844      *                     {@code subscriberId} with wifi network type to receive usage for
845      *                     wifi networks which is under the given subscription if applicable.
846      *                     Otherwise, pass {@code null} when querying all wifi networks.
847      * @param thresholdBytes Threshold in bytes to be notified on.
848      * @param callback The {@link UsageCallback} that the system will call when data usage
849      *            has exceeded the specified threshold.
850      */
registerUsageCallback(int networkType, @Nullable String subscriberId, long thresholdBytes, @NonNull UsageCallback callback)851     public void registerUsageCallback(int networkType, @Nullable String subscriberId,
852             long thresholdBytes, @NonNull UsageCallback callback) {
853         registerUsageCallback(networkType, subscriberId, thresholdBytes, callback,
854                 null /* handler */);
855     }
856 
857     /**
858      * Registers to receive notifications about data usage on specified networks.
859      *
860      * <p>The callbacks will continue to be called as long as the process is live or
861      * {@link #unregisterUsageCallback} is called.
862      *
863      * @param networkType Type of network to monitor. Either
864                   {@link ConnectivityManager#TYPE_MOBILE} or {@link ConnectivityManager#TYPE_WIFI}.
865      * @param subscriberId If applicable, the subscriber id of the network interface.
866      *                     <p>Starting with API level 29, the {@code subscriberId} is guarded by
867      *                     additional restrictions. Calling apps that do not meet the new
868      *                     requirements to access the {@code subscriberId} can provide a {@code
869      *                     null} value when registering for the mobile network type to receive
870      *                     notifications for all mobile networks. For additional details see {@link
871      *                     TelephonyManager#getSubscriberId()}.
872      *                     <p>Starting with API level 31, calling apps can provide a
873      *                     {@code subscriberId} with wifi network type to receive usage for
874      *                     wifi networks which is under the given subscription if applicable.
875      *                     Otherwise, pass {@code null} when querying all wifi networks.
876      * @param thresholdBytes Threshold in bytes to be notified on.
877      * @param callback The {@link UsageCallback} that the system will call when data usage
878      *            has exceeded the specified threshold.
879      * @param handler to dispatch callback events through, otherwise if {@code null} it uses
880      *            the calling thread.
881      */
registerUsageCallback(int networkType, @Nullable String subscriberId, long thresholdBytes, @NonNull UsageCallback callback, @Nullable Handler handler)882     public void registerUsageCallback(int networkType, @Nullable String subscriberId,
883             long thresholdBytes, @NonNull UsageCallback callback, @Nullable Handler handler) {
884         NetworkTemplate template = createTemplate(networkType, subscriberId);
885         if (DBG) {
886             Log.d(TAG, "registerUsageCallback called with: {"
887                     + " networkType=" + networkType
888                     + " subscriberId=" + subscriberId
889                     + " thresholdBytes=" + thresholdBytes
890                     + " }");
891         }
892 
893         final Executor executor = handler == null ? r -> r.run() : r -> handler.post(r);
894 
895         registerUsageCallback(template, thresholdBytes, executor, callback);
896     }
897 
898     /**
899      * Unregisters callbacks on data usage.
900      *
901      * @param callback The {@link UsageCallback} used when registering.
902      */
unregisterUsageCallback(@onNull UsageCallback callback)903     public void unregisterUsageCallback(@NonNull UsageCallback callback) {
904         if (callback == null || callback.request == null
905                 || callback.request.requestId == DataUsageRequest.REQUEST_ID_UNSET) {
906             throw new IllegalArgumentException("Invalid UsageCallback");
907         }
908         try {
909             mService.unregisterUsageRequest(callback.request);
910         } catch (RemoteException e) {
911             if (DBG) Log.d(TAG, "Remote exception when unregistering callback");
912             throw e.rethrowFromSystemServer();
913         }
914     }
915 
916     /**
917      * Base class for usage callbacks. Should be extended by applications wanting notifications.
918      */
919     public static abstract class UsageCallback {
920         /**
921          * Called when data usage has reached the given threshold.
922          *
923          * Called by {@code NetworkStatsService} when the registered threshold is reached.
924          * If a caller implements {@link #onThresholdReached(NetworkTemplate)}, the system
925          * will not call {@link #onThresholdReached(int, String)}.
926          *
927          * @param template The {@link NetworkTemplate} that associated with this callback.
928          * @hide
929          */
930         @SystemApi(client = MODULE_LIBRARIES)
onThresholdReached(@onNull NetworkTemplate template)931         public void onThresholdReached(@NonNull NetworkTemplate template) {
932             // Backward compatibility for those who didn't override this function.
933             final int networkType = networkTypeForTemplate(template);
934             if (networkType != ConnectivityManager.TYPE_NONE) {
935                 final String subscriberId = template.getSubscriberIds().isEmpty() ? null
936                         : template.getSubscriberIds().iterator().next();
937                 onThresholdReached(networkType, subscriberId);
938             }
939         }
940 
941         /**
942          * Called when data usage has reached the given threshold.
943          */
onThresholdReached(int networkType, @Nullable String subscriberId)944         public abstract void onThresholdReached(int networkType, @Nullable String subscriberId);
945 
946         /**
947          * @hide used for internal bookkeeping
948          */
949         private DataUsageRequest request;
950 
951         /**
952          * Get network type from a template if feasible.
953          *
954          * @param template the target {@link NetworkTemplate}.
955          * @return legacy network type, only supports for the types which is already supported in
956          *         {@link #registerUsageCallback(int, String, long, UsageCallback, Handler)}.
957          *         {@link ConnectivityManager#TYPE_NONE} for other types.
958          */
networkTypeForTemplate(@onNull NetworkTemplate template)959         private static int networkTypeForTemplate(@NonNull NetworkTemplate template) {
960             switch (template.getMatchRule()) {
961                 case NetworkTemplate.MATCH_MOBILE:
962                     return ConnectivityManager.TYPE_MOBILE;
963                 case NetworkTemplate.MATCH_WIFI:
964                     return ConnectivityManager.TYPE_WIFI;
965                 default:
966                     return ConnectivityManager.TYPE_NONE;
967             }
968         }
969     }
970 
971     /**
972      * Registers a custom provider of {@link android.net.NetworkStats} to provide network statistics
973      * to the system. To unregister, invoke {@link #unregisterNetworkStatsProvider}.
974      * Note that no de-duplication of statistics between providers is performed, so each provider
975      * must only report network traffic that is not being reported by any other provider. Also note
976      * that the provider cannot be re-registered after unregistering.
977      *
978      * @param tag a human readable identifier of the custom network stats provider. This is only
979      *            used for debugging.
980      * @param provider the subclass of {@link NetworkStatsProvider} that needs to be
981      *                 registered to the system.
982      * @hide
983      */
984     @SystemApi
985     @RequiresPermission(anyOf = {
986             android.Manifest.permission.NETWORK_STATS_PROVIDER,
987             NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
registerNetworkStatsProvider( @onNull String tag, @NonNull NetworkStatsProvider provider)988     public void registerNetworkStatsProvider(
989             @NonNull String tag,
990             @NonNull NetworkStatsProvider provider) {
991         try {
992             if (provider.getProviderCallbackBinder() != null) {
993                 throw new IllegalArgumentException("provider is already registered");
994             }
995             final INetworkStatsProviderCallback cbBinder =
996                     mService.registerNetworkStatsProvider(tag, provider.getProviderBinder());
997             provider.setProviderCallbackBinder(cbBinder);
998         } catch (RemoteException e) {
999             e.rethrowAsRuntimeException();
1000         }
1001     }
1002 
1003     /**
1004      * Unregisters an instance of {@link NetworkStatsProvider}.
1005      *
1006      * @param provider the subclass of {@link NetworkStatsProvider} that needs to be
1007      *                 unregistered to the system.
1008      * @hide
1009      */
1010     @SystemApi
1011     @RequiresPermission(anyOf = {
1012             android.Manifest.permission.NETWORK_STATS_PROVIDER,
1013             NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
unregisterNetworkStatsProvider(@onNull NetworkStatsProvider provider)1014     public void unregisterNetworkStatsProvider(@NonNull NetworkStatsProvider provider) {
1015         try {
1016             provider.getProviderCallbackBinderOrThrow().unregister();
1017         } catch (RemoteException e) {
1018             e.rethrowAsRuntimeException();
1019         }
1020     }
1021 
createTemplate(int networkType, @Nullable String subscriberId)1022     private static NetworkTemplate createTemplate(int networkType, @Nullable String subscriberId) {
1023         final NetworkTemplate template;
1024         switch (networkType) {
1025             case ConnectivityManager.TYPE_MOBILE:
1026                 template = subscriberId == null
1027                         ? new NetworkTemplate.Builder(MATCH_MOBILE)
1028                                 .setMeteredness(METERED_YES).build()
1029                         : new NetworkTemplate.Builder(MATCH_MOBILE)
1030                                 .setMeteredness(METERED_YES)
1031                                 .setSubscriberIds(Set.of(subscriberId)).build();
1032                 break;
1033             case ConnectivityManager.TYPE_WIFI:
1034                 template = TextUtils.isEmpty(subscriberId)
1035                         ? new NetworkTemplate.Builder(MATCH_WIFI).build()
1036                         : new  NetworkTemplate.Builder(MATCH_WIFI)
1037                                 .setSubscriberIds(Set.of(subscriberId)).build();
1038                 break;
1039             default:
1040                 throw new IllegalArgumentException("Cannot create template for network type "
1041                         + networkType + ", subscriberId '"
1042                         + NetworkIdentityUtils.scrubSubscriberId(subscriberId) + "'.");
1043         }
1044         return template;
1045     }
1046 
1047     /**
1048      * Notify {@code NetworkStatsService} about network status changed.
1049      *
1050      * Notifies NetworkStatsService of network state changes for data usage accounting purposes.
1051      *
1052      * To avoid races that attribute data usage to wrong network, such as new network with
1053      * the same interface after SIM hot-swap, this function will not return until
1054      * {@code NetworkStatsService} finishes its work of retrieving traffic statistics from
1055      * all data sources.
1056      *
1057      * @param defaultNetworks the list of all networks that could be used by network traffic that
1058      *                        does not explicitly select a network.
1059      * @param networkStateSnapshots a list of {@link NetworkStateSnapshot}s, one for
1060      *                              each network that is currently connected.
1061      * @param activeIface the active (i.e., connected) default network interface for the calling
1062      *                    uid. Used to determine on which network future calls to
1063      *                    {@link android.net.TrafficStats#incrementOperationCount} applies to.
1064      * @param underlyingNetworkInfos the list of underlying network information for all
1065      *                               currently-connected VPNs.
1066      *
1067      * @hide
1068      */
1069     @SystemApi(client = MODULE_LIBRARIES)
1070     @RequiresPermission(anyOf = {
1071             NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1072             android.Manifest.permission.NETWORK_STACK})
notifyNetworkStatus( @onNull List<Network> defaultNetworks, @NonNull List<NetworkStateSnapshot> networkStateSnapshots, @Nullable String activeIface, @NonNull List<UnderlyingNetworkInfo> underlyingNetworkInfos)1073     public void notifyNetworkStatus(
1074             @NonNull List<Network> defaultNetworks,
1075             @NonNull List<NetworkStateSnapshot> networkStateSnapshots,
1076             @Nullable String activeIface,
1077             @NonNull List<UnderlyingNetworkInfo> underlyingNetworkInfos) {
1078         try {
1079             Objects.requireNonNull(defaultNetworks);
1080             Objects.requireNonNull(networkStateSnapshots);
1081             Objects.requireNonNull(underlyingNetworkInfos);
1082             mService.notifyNetworkStatus(defaultNetworks.toArray(new Network[0]),
1083                     networkStateSnapshots.toArray(new NetworkStateSnapshot[0]), activeIface,
1084                     underlyingNetworkInfos.toArray(new UnderlyingNetworkInfo[0]));
1085         } catch (RemoteException e) {
1086             throw e.rethrowFromSystemServer();
1087         }
1088     }
1089 
1090     private static class UsageCallbackWrapper extends IUsageCallback.Stub {
1091         // Null if unregistered.
1092         private volatile UsageCallback mCallback;
1093 
1094         private final Executor mExecutor;
1095 
UsageCallbackWrapper(@onNull Executor executor, @NonNull UsageCallback callback)1096         UsageCallbackWrapper(@NonNull Executor executor, @NonNull UsageCallback callback) {
1097             mCallback = callback;
1098             mExecutor = executor;
1099         }
1100 
1101         @Override
onThresholdReached(DataUsageRequest request)1102         public void onThresholdReached(DataUsageRequest request) {
1103             // Copy it to a local variable in case mCallback changed inside the if condition.
1104             final UsageCallback callback = mCallback;
1105             if (callback != null) {
1106                 mExecutor.execute(() -> callback.onThresholdReached(request.template));
1107             } else {
1108                 Log.e(TAG, "onThresholdReached with released callback for " + request);
1109             }
1110         }
1111 
1112         @Override
onCallbackReleased(DataUsageRequest request)1113         public void onCallbackReleased(DataUsageRequest request) {
1114             if (DBG) Log.d(TAG, "callback released for " + request);
1115             mCallback = null;
1116         }
1117     }
1118 
1119     /**
1120      * Mark given UID as being in foreground for stats purposes.
1121      *
1122      * @hide
1123      */
1124     @SystemApi(client = MODULE_LIBRARIES)
1125     @RequiresPermission(anyOf = {
1126             NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1127             android.Manifest.permission.NETWORK_STACK})
noteUidForeground(int uid, boolean uidForeground)1128     public void noteUidForeground(int uid, boolean uidForeground) {
1129         try {
1130             mService.noteUidForeground(uid, uidForeground);
1131         } catch (RemoteException e) {
1132             throw e.rethrowFromSystemServer();
1133         }
1134     }
1135 
1136     /**
1137      * Set default value of global alert bytes, the value will be clamped to [128kB, 2MB].
1138      *
1139      * @hide
1140      */
1141     @SystemApi(client = MODULE_LIBRARIES)
1142     @RequiresPermission(anyOf = {
1143             NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1144             Manifest.permission.NETWORK_STACK})
setDefaultGlobalAlert(long alertBytes)1145     public void setDefaultGlobalAlert(long alertBytes) {
1146         try {
1147             // TODO: Sync internal naming with the API surface.
1148             mService.advisePersistThreshold(alertBytes);
1149         } catch (RemoteException e) {
1150             throw e.rethrowFromSystemServer();
1151         }
1152     }
1153 
1154     /**
1155      * Force update of statistics.
1156      *
1157      * @hide
1158      */
1159     @SystemApi(client = MODULE_LIBRARIES)
1160     @RequiresPermission(anyOf = {
1161             NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1162             android.Manifest.permission.NETWORK_STACK})
forceUpdate()1163     public void forceUpdate() {
1164         try {
1165             mService.forceUpdate();
1166         } catch (RemoteException e) {
1167             throw e.rethrowFromSystemServer();
1168         }
1169     }
1170 
1171     /**
1172      * Set the warning and limit to all registered custom network stats providers.
1173      * Note that invocation of any interface will be sent to all providers.
1174      *
1175      * Asynchronicity notes : because traffic may be happening on the device at the same time, it
1176      * doesn't make sense to wait for the warning and limit to be set – a caller still wouldn't
1177      * know when exactly it was effective. All that can matter is that it's done quickly. Also,
1178      * this method can't fail, so there is no status to return. All providers will see the new
1179      * values soon.
1180      * As such, this method returns immediately and sends the warning and limit to all providers
1181      * as soon as possible through a one-way binder call.
1182      *
1183      * @hide
1184      */
1185     @SystemApi(client = MODULE_LIBRARIES)
1186     @RequiresPermission(anyOf = {
1187             NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1188             android.Manifest.permission.NETWORK_STACK})
setStatsProviderWarningAndLimitAsync(@onNull String iface, long warning, long limit)1189     public void setStatsProviderWarningAndLimitAsync(@NonNull String iface, long warning,
1190             long limit) {
1191         try {
1192             mService.setStatsProviderWarningAndLimitAsync(iface, warning, limit);
1193         } catch (RemoteException e) {
1194             throw e.rethrowFromSystemServer();
1195         }
1196     }
1197 
1198     /**
1199      * Get a RAT type representative of a group of RAT types for network statistics.
1200      *
1201      * Collapse the given Radio Access Technology (RAT) type into a bucket that
1202      * is representative of the original RAT type for network statistics. The
1203      * mapping mostly corresponds to {@code TelephonyManager#NETWORK_CLASS_BIT_MASK_*}
1204      * but with adaptations specific to the virtual types introduced by
1205      * networks stats.
1206      *
1207      * @param ratType An integer defined in {@code TelephonyManager#NETWORK_TYPE_*}.
1208      *
1209      * @hide
1210      */
1211     @SystemApi(client = MODULE_LIBRARIES)
getCollapsedRatType(int ratType)1212     public static int getCollapsedRatType(int ratType) {
1213         switch (ratType) {
1214             case TelephonyManager.NETWORK_TYPE_GPRS:
1215             case TelephonyManager.NETWORK_TYPE_GSM:
1216             case TelephonyManager.NETWORK_TYPE_EDGE:
1217             case TelephonyManager.NETWORK_TYPE_IDEN:
1218             case TelephonyManager.NETWORK_TYPE_CDMA:
1219             case TelephonyManager.NETWORK_TYPE_1xRTT:
1220                 return TelephonyManager.NETWORK_TYPE_GSM;
1221             case TelephonyManager.NETWORK_TYPE_EVDO_0:
1222             case TelephonyManager.NETWORK_TYPE_EVDO_A:
1223             case TelephonyManager.NETWORK_TYPE_EVDO_B:
1224             case TelephonyManager.NETWORK_TYPE_EHRPD:
1225             case TelephonyManager.NETWORK_TYPE_UMTS:
1226             case TelephonyManager.NETWORK_TYPE_HSDPA:
1227             case TelephonyManager.NETWORK_TYPE_HSUPA:
1228             case TelephonyManager.NETWORK_TYPE_HSPA:
1229             case TelephonyManager.NETWORK_TYPE_HSPAP:
1230             case TelephonyManager.NETWORK_TYPE_TD_SCDMA:
1231                 return TelephonyManager.NETWORK_TYPE_UMTS;
1232             case TelephonyManager.NETWORK_TYPE_LTE:
1233             case TelephonyManager.NETWORK_TYPE_IWLAN:
1234                 return TelephonyManager.NETWORK_TYPE_LTE;
1235             case TelephonyManager.NETWORK_TYPE_NR:
1236                 return TelephonyManager.NETWORK_TYPE_NR;
1237             // Virtual RAT type for 5G NSA mode, see
1238             // {@link NetworkStatsManager#NETWORK_TYPE_5G_NSA}.
1239             case NetworkStatsManager.NETWORK_TYPE_5G_NSA:
1240                 return NetworkStatsManager.NETWORK_TYPE_5G_NSA;
1241             default:
1242                 return TelephonyManager.NETWORK_TYPE_UNKNOWN;
1243         }
1244     }
1245 }
1246