方案一
NetworkStatsManager#querySummary
/**
* Query network usage statistics summaries. Result filtered to include only uids belonging to
* calling user. Result is aggregated over time, hence all buckets will have the same start and
* end timestamps. Not aggregated over state, uid, metered, or roaming. This means buckets'
* start and end timestamps are going to be the same as the 'startTime' and 'endTime'
* parameters. State, uid, metered, and roaming are going to vary, and tag is going to be the
* same.
*
* @param networkType As defined in {@link ConnectivityManager}, e.g.
* {@link ConnectivityManager#TYPE_MOBILE}, {@link ConnectivityManager#TYPE_WIFI}
* etc.
* @param subscriberId If applicable, the subscriber id of the network interface.
* @param startTime Start of period. Defined in terms of "Unix time", see
* {@link java.lang.System#currentTimeMillis}.
* @param endTime End of period. Defined in terms of "Unix time", see
* {@link java.lang.System#currentTimeMillis}.
* @return Statistics object or null if permissions are insufficient or error happened during
* statistics collection.
*/
public NetworkStats querySummary(int networkType, String subscriberId, long startTime,
long endTime) throws SecurityException, RemoteException {
NetworkTemplate template;
try {
template = createTemplate(networkType, subscriberId);
} catch (IllegalArgumentException e) {
if (DBG) Log.e(TAG, "Cannot create template", e);
return null;
}
NetworkStats result;
result = new NetworkStats(mContext, template, startTime, endTime);
result.startSummaryEnumeration();
return result;
}
NetworkStats.Bucket#getRxBytes
/**
* Number of bytes received during the bucket's time interval. Statistics are measured at
* the network layer, so they include both TCP and UDP usage.
* @return Number of bytes.
*/
public long getRxBytes() {
return mRxBytes;
}