blob: af7c053a417d6be6c2ea5af2f5156d5212abc5ab [file] [log] [blame]
Zoltan Szatmary-Ban9c5dfa52015-02-23 17:20:20 +00001/**
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
17package android.app.usage;
18
19import android.app.usage.NetworkUsageStats.Bucket;
20import android.content.Context;
21import android.net.ConnectivityManager;
22import android.net.NetworkIdentity;
23import android.net.NetworkTemplate;
24import android.os.RemoteException;
25import android.os.UserHandle;
26import android.util.Log;
27
28/**
29 * Provides access to network usage history and statistics. Usage data is collected in
30 * discrete bins of time called 'Buckets'. See {@link NetworkUsageStats.Bucket} for details.
31 * <p />
32 * Queries can define a time interval in the form of start and end timestamps (Long.MIN_VALUE and
33 * Long.MAX_VALUE can be used to simulate open ended intervals). All queries (except
34 * {@link #querySummaryForDevice}) collect only network usage of apps belonging to the same user
35 * as the client. In addition tethering usage, usage by removed users and apps, and usage by system
36 * is also included in the results.
37 * <h3>
38 * Summary queries
39 * </h3>
40 * These queries aggregate network usage across the whole interval. Therefore there will be only one
41 * bucket for a particular key and state combination. In case of the user-wide and device-wide
42 * summaries a single bucket containing the totalised network usage is returned.
43 * <h3>
44 * History queries
45 * </h3>
46 * These queries do not aggregate over time but do aggregate over state. Therefore there can be
47 * multiple buckets for a particular key but all Bucket's state is going to be
48 * {@link NetworkUsageStats.Bucket#STATE_ALL}.
49 * <p />
50 * <b>NOTE:</b> This API requires the permission
51 * {@link android.Manifest.permission#PACKAGE_USAGE_STATS}, which is a system-level permission and
52 * will not be granted to third-party apps. However, declaring the permission implies intention to
53 * use the API and the user of the device can grant permission through the Settings application.
54 * Profile owner apps are automatically granted permission to query data on the profile they manage
55 * (that is, for any query except {@link #querySummaryForDevice}). Device owner apps likewise get
56 * access to usage data of the primary user.
57 */
58public class NetworkStatsManager {
59 private final static String TAG = "NetworkStatsManager";
60
61 private final Context mContext;
62
63 /**
64 * {@hide}
65 */
66 public NetworkStatsManager(Context context) {
67 mContext = context;
68 }
69 /**
70 * Query network usage statistics summaries. Result is summarised data usage for the whole
71 * device. Result is a single Bucket aggregated over time, state and uid.
72 *
73 * @param networkType As defined in {@link ConnectivityManager}, e.g.
74 * {@link ConnectivityManager#TYPE_MOBILE}, {@link ConnectivityManager#TYPE_WIFI}
75 * etc.
76 * @param subscriberId If applicable, the subscriber id of the network interface.
77 * @param startTime Start of period. Defined in terms of "Unix time", see
78 * {@link java.lang.System#currentTimeMillis}.
79 * @param endTime End of period. Defined in terms of "Unix time", see
80 * {@link java.lang.System#currentTimeMillis}.
81 * @return Bucket object or null if permissions are insufficient or error happened during
82 * statistics collection.
83 */
84 public Bucket querySummaryForDevice(int networkType, String subscriberId,
85 long startTime, long endTime) throws SecurityException, RemoteException {
86 NetworkTemplate template = createTemplate(networkType, subscriberId);
87 if (template == null) {
88 return null;
89 }
90
91 Bucket bucket = null;
92 NetworkUsageStats stats = new NetworkUsageStats(mContext, template, startTime, endTime);
93 bucket = stats.getDeviceSummaryForNetwork(startTime, endTime);
94
95 stats.close();
96 return bucket;
97 }
98
99 /**
100 * Query network usage statistics summaries. Result is summarised data usage for all uids
101 * belonging to calling user. Result is a single Bucket aggregated over time, state and uid.
102 *
103 * @param networkType As defined in {@link ConnectivityManager}, e.g.
104 * {@link ConnectivityManager#TYPE_MOBILE}, {@link ConnectivityManager#TYPE_WIFI}
105 * etc.
106 * @param subscriberId If applicable, the subscriber id of the network interface.
107 * @param startTime Start of period. Defined in terms of "Unix time", see
108 * {@link java.lang.System#currentTimeMillis}.
109 * @param endTime End of period. Defined in terms of "Unix time", see
110 * {@link java.lang.System#currentTimeMillis}.
111 * @return Bucket object or null if permissions are insufficient or error happened during
112 * statistics collection.
113 */
114 public Bucket querySummaryForUser(int networkType, String subscriberId, long startTime,
115 long endTime) throws SecurityException, RemoteException {
116 NetworkTemplate template = createTemplate(networkType, subscriberId);
117 if (template == null) {
118 return null;
119 }
120
121 NetworkUsageStats stats;
122 stats = new NetworkUsageStats(mContext, template, startTime, endTime);
123 stats.startSummaryEnumeration(startTime, endTime);
124
125 stats.close();
126 return stats.getSummaryAggregate();
127 }
128
129 /**
130 * Query network usage statistics summaries. Result filtered to include only uids belonging to
131 * calling user. Result is aggregated over time, hence all buckets will have the same start and
132 * end timestamps. Not aggregated over state or uid.
133 *
134 * @param networkType As defined in {@link ConnectivityManager}, e.g.
135 * {@link ConnectivityManager#TYPE_MOBILE}, {@link ConnectivityManager#TYPE_WIFI}
136 * etc.
137 * @param subscriberId If applicable, the subscriber id of the network interface.
138 * @param startTime Start of period. Defined in terms of "Unix time", see
139 * {@link java.lang.System#currentTimeMillis}.
140 * @param endTime End of period. Defined in terms of "Unix time", see
141 * {@link java.lang.System#currentTimeMillis}.
142 * @return Statistics object or null if permissions are insufficient or error happened during
143 * statistics collection.
144 */
145 public NetworkUsageStats querySummary(int networkType, String subscriberId, long startTime,
146 long endTime) throws SecurityException, RemoteException {
147 NetworkTemplate template = createTemplate(networkType, subscriberId);
148 if (template == null) {
149 return null;
150 }
151
152 NetworkUsageStats result;
153 result = new NetworkUsageStats(mContext, template, startTime, endTime);
154 result.startSummaryEnumeration(startTime, endTime);
155
156 return result;
157 }
158
159 /**
160 * Query network usage statistics details. Only usable for uids belonging to calling user.
161 * Result is aggregated over state but not aggregated over time.
162 *
163 * @param networkType As defined in {@link ConnectivityManager}, e.g.
164 * {@link ConnectivityManager#TYPE_MOBILE}, {@link ConnectivityManager#TYPE_WIFI}
165 * etc.
166 * @param subscriberId If applicable, the subscriber id of the network interface.
167 * @param startTime Start of period. Defined in terms of "Unix time", see
168 * {@link java.lang.System#currentTimeMillis}.
169 * @param endTime End of period. Defined in terms of "Unix time", see
170 * {@link java.lang.System#currentTimeMillis}.
171 * @param uid UID of app
172 * @return Statistics object or null if permissions are insufficient or error happened during
173 * statistics collection.
174 */
175 public NetworkUsageStats queryDetailsForUid(int networkType, String subscriberId,
176 long startTime, long endTime, int uid) throws SecurityException, RemoteException {
177 NetworkTemplate template = createTemplate(networkType, subscriberId);
178 if (template == null) {
179 return null;
180 }
181
182 NetworkUsageStats result;
183 result = new NetworkUsageStats(mContext, template, startTime, endTime);
184 result.startHistoryEnumeration(uid);
185
186 return result;
187 }
188
189 /**
190 * Query network usage statistics details. Result filtered to include only uids belonging to
191 * calling user. Result is aggregated over state but not aggregated over time or uid.
192 *
193 * @param networkType As defined in {@link ConnectivityManager}, e.g.
194 * {@link ConnectivityManager#TYPE_MOBILE}, {@link ConnectivityManager#TYPE_WIFI}
195 * etc.
196 * @param subscriberId If applicable, the subscriber id of the network interface.
197 * @param startTime Start of period. Defined in terms of "Unix time", see
198 * {@link java.lang.System#currentTimeMillis}.
199 * @param endTime End of period. Defined in terms of "Unix time", see
200 * {@link java.lang.System#currentTimeMillis}.
201 * @return Statistics object or null if permissions are insufficient or error happened during
202 * statistics collection.
203 */
204 public NetworkUsageStats queryDetails(int networkType, String subscriberId, long startTime,
205 long endTime) throws SecurityException, RemoteException {
206 NetworkTemplate template = createTemplate(networkType, subscriberId);
207 if (template == null) {
208 return null;
209 }
210 NetworkUsageStats result;
211 result = new NetworkUsageStats(mContext, template, startTime, endTime);
212 result.startUserUidEnumeration();
213 return result;
214 }
215
216 private static NetworkTemplate createTemplate(int networkType, String subscriberId) {
217 NetworkTemplate template = null;
218 switch (networkType) {
219 case ConnectivityManager.TYPE_MOBILE: {
220 template = NetworkTemplate.buildTemplateMobileAll(subscriberId);
221 } break;
222 case ConnectivityManager.TYPE_WIFI: {
223 template = NetworkTemplate.buildTemplateWifiWildcard();
224 } break;
225 default: {
226 Log.w(TAG, "Cannot create template for network type " + networkType
227 + ", subscriberId '" + NetworkIdentity.scrubSubscriberId(subscriberId) +
228 "'.");
229 }
230 }
231 return template;
232 }
233}