下面列出了怎么用android.app.usage.NetworkStatsManager的API类实例代码及写法,或者点击链接到github查看源代码。
public void start() {
mCM = mContext.getSystemService(ConnectivityManager.class);
mNPM = mContext.getSystemService(NetworkPolicyManager.class);
mStatsManager = mContext.getSystemService(NetworkStatsManager.class);
registerTrackMobileCallback();
registerNetworkPolicyListener();
final Uri defaultSettingUri =
Settings.Global.getUriFor(NETWORK_DEFAULT_DAILY_MULTIPATH_QUOTA_BYTES);
mResolver.registerContentObserver(defaultSettingUri, false, mSettingsObserver);
final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_CONFIGURATION_CHANGED);
mContext.registerReceiverAsUser(
mConfigChangeReceiver, UserHandle.ALL, intentFilter, null, mHandler);
}
/**
* Find the most relevant {@link SubscriptionPlan} for the given
* {@link NetworkTemplate} and flags. This is typically used to augment
* local measurement results to match a known anchor from the carrier.
*/
private SubscriptionPlan resolveSubscriptionPlan(NetworkTemplate template, int flags) {
SubscriptionPlan plan = null;
if ((flags & NetworkStatsManager.FLAG_AUGMENT_WITH_SUBSCRIPTION_PLAN) != 0
&& mSettings.getAugmentEnabled()) {
if (LOGD) Slog.d(TAG, "Resolving plan for " + template);
final long token = Binder.clearCallingIdentity();
try {
plan = LocalServices.getService(NetworkPolicyManagerInternal.class)
.getSubscriptionPlan(template);
} finally {
Binder.restoreCallingIdentity(token);
}
if (LOGD) Slog.d(TAG, "Resolved to plan " + plan);
}
return plan;
}
/**
* Removes a {@link DataUsageRequest} if the calling uid is authorized.
* Should only be called from the handler thread otherwise there will be a race condition
* on mDataUsageRequests.
*/
private void handleUnregister(DataUsageRequest request, int callingUid) {
RequestInfo requestInfo;
requestInfo = mDataUsageRequests.get(request.requestId);
if (requestInfo == null) {
if (LOGV) Slog.v(TAG, "Trying to unregister unknown request " + request);
return;
}
if (Process.SYSTEM_UID != callingUid && requestInfo.mCallingUid != callingUid) {
Slog.w(TAG, "Caller uid " + callingUid + " is not owner of " + request);
return;
}
if (LOGV) Slog.v(TAG, "Unregistering " + request);
mDataUsageRequests.remove(request.requestId);
requestInfo.unlinkDeathRecipient();
requestInfo.callCallback(NetworkStatsManager.CALLBACK_RELEASED);
}
private long getNetworkTotalBytes(NetworkTemplate template, long start, long end) {
assertSystemReady();
assertBandwidthControlEnabled();
// NOTE: if callers want to get non-augmented data, they should go
// through the public API
return internalGetSummaryForNetwork(template,
NetworkStatsManager.FLAG_AUGMENT_WITH_SUBSCRIPTION_PLAN, start, end,
NetworkStatsAccess.Level.DEVICE, Binder.getCallingUid()).getTotalBytes();
}
@Override
public void binderDied() {
if (LOGV) Slog.v(TAG, "RequestInfo binderDied("
+ mRequest + ", " + mBinder + ")");
mStatsObserver.unregister(mRequest, Process.SYSTEM_UID);
callCallback(NetworkStatsManager.CALLBACK_RELEASED);
}
/**
* Update stats given the samples and interface to identity mappings.
*/
private void updateStats(StatsContext statsContext) {
if (mRecorder == null) {
// First run; establish baseline stats
resetRecorder();
recordSample(statsContext);
return;
}
recordSample(statsContext);
if (checkStats()) {
resetRecorder();
callCallback(NetworkStatsManager.CALLBACK_LIMIT_REACHED);
}
}
private String callbackTypeToName(int callbackType) {
switch (callbackType) {
case NetworkStatsManager.CALLBACK_LIMIT_REACHED:
return "LIMIT_REACHED";
case NetworkStatsManager.CALLBACK_RELEASED:
return "RELEASED";
default:
return "UNKNOWN";
}
}
/**
* Given the start time and end time, then you can get the traffic usage during this time.
*
* @param startTime Start of period. Defined in terms of "Unix time", see
* {@link System#currentTimeMillis}.
* @param endTime End of period. Defined in terms of "Unix time", see
* {@link System#currentTimeMillis}.
* @param netType the netWorkType you want to query
* @return Number of bytes.
*/
@RequiresApi(api = Build.VERSION_CODES.M)
public static long getNetStats(@NonNull Context context, long startTime, long endTime, int netType) {
long netDataReceive = 0;
long netDataSend = 0;
String subId = null;
NetworkStatsManager manager = (NetworkStatsManager) context.getApplicationContext().
getSystemService(Context.NETWORK_STATS_SERVICE);
if (manager == null) {
return 0;
}
NetworkStats networkStats = null;
NetworkStats.Bucket bucket = new NetworkStats.Bucket();
try {
networkStats = manager.querySummary(netType, subId, startTime, endTime);
} catch (Exception e) {
e.printStackTrace();
}
while (networkStats != null && networkStats.hasNextBucket()) {
networkStats.getNextBucket(bucket);
int uid = bucket.getUid();
if (getAppUid(context) == uid) {
netDataReceive += bucket.getRxBytes();
netDataSend += bucket.getTxBytes();
}
}
return (netDataReceive + netDataSend);
}
private Map<String, Long> getMobileData(Context context, TelephonyManager tm, NetworkStatsManager nsm, int offset) {
Map<String, Long> result = new HashMap<>();
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
long[] range = AppUtil.getTimeRange(SortEnum.getSortEnum(offset));
NetworkStats networkStatsM;
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
networkStatsM = nsm.querySummary(ConnectivityManager.TYPE_MOBILE, null, range[0], range[1]);
if (networkStatsM != null) {
while (networkStatsM.hasNextBucket()) {
NetworkStats.Bucket bucket = new NetworkStats.Bucket();
networkStatsM.getNextBucket(bucket);
String key = "u" + bucket.getUid();
Log.d("******", key + " " + bucket.getTxBytes() + "");
if (result.containsKey(key)) {
result.put(key, result.get(key) + bucket.getTxBytes() + bucket.getRxBytes());
} else {
result.put(key, bucket.getTxBytes() + bucket.getRxBytes());
}
}
}
}
} catch (RemoteException e) {
e.printStackTrace();
Log.e(">>>>>", e.getMessage());
}
}
return result;
}
void updateMultipathBudget() {
long quota = LocalServices.getService(NetworkPolicyManagerInternal.class)
.getSubscriptionOpportunisticQuota(this.network, QUOTA_TYPE_MULTIPATH);
if (DBG) Slog.d(TAG, "Opportunistic quota from data plan: " + quota + " bytes");
// Fallback to user settings-based quota if not available from phone plan
if (quota == OPPORTUNISTIC_QUOTA_UNKNOWN) {
quota = getUserPolicyOpportunisticQuotaBytes();
if (DBG) Slog.d(TAG, "Opportunistic quota from user policy: " + quota + " bytes");
}
if (quota == OPPORTUNISTIC_QUOTA_UNKNOWN) {
quota = getDefaultDailyMultipathQuotaBytes();
if (DBG) Slog.d(TAG, "Setting quota: " + quota + " bytes");
}
// TODO: re-register if day changed: budget may have run out but should be refreshed.
if (haveMultipathBudget() && quota == mQuota) {
// If there is already a usage callback pending , there's no need to re-register it
// if the quota hasn't changed. The callback will simply fire as expected when the
// budget is spent.
if (DBG) Slog.d(TAG, "Quota still " + quota + ", not updating.");
return;
}
mQuota = quota;
// If we can't get current usage, assume the worst and don't give
// ourselves any budget to work with.
final long usage = getDailyNonDefaultDataUsage();
final long budget = (usage == -1) ? 0 : Math.max(0, quota - usage);
// Only consider budgets greater than MIN_THRESHOLD_BYTES, otherwise the callback will
// fire late, after data usage went over budget. Also budget should be 0 if remaining
// data is close to 0.
// This is necessary because the usage callback does not accept smaller thresholds.
// Because it snaps everything to MIN_THRESHOLD_BYTES, the lesser of the two evils is
// to snap to 0 here.
// This will only be called if the total quota for the day changed, not if usage changed
// since last time, so even if this is called very often the budget will not snap to 0
// as soon as there are less than 2MB left for today.
if (budget > NetworkStatsManager.MIN_THRESHOLD_BYTES) {
if (DBG) Slog.d(TAG, "Setting callback for " + budget +
" bytes on network " + network);
registerUsageCallback(budget);
} else {
maybeUnregisterUsageCallback();
}
}
@Override
public INetworkStatsSession openSession() {
// NOTE: if callers want to get non-augmented data, they should go
// through the public API
return openSessionInternal(NetworkStatsManager.FLAG_AUGMENT_WITH_SUBSCRIPTION_PLAN, null);
}
@Override
public NetworkStatsManager createService(ContextImpl ctx) throws ServiceNotFoundException {
return new NetworkStatsManager(ctx.getOuterContext());
}
@TargetApi(23)
public static NetworkStatsManager getNetworkStatsManager() {
return (NetworkStatsManager) getSystemService(Context.NETWORK_STATS_SERVICE);
}
@TargetApi(Build.VERSION_CODES.M)
public NetUtilAboveM(Context context) {
NetworkStatsManager networkStatsManager = (NetworkStatsManager) context.getSystemService(context.NETWORK_STATS_SERVICE);
}
public NetworkStatsManagerBytesCollector(Context context) {
mNetworkStatsManager = context.getSystemService(NetworkStatsManager.class);
mStartTime = Long.MIN_VALUE;
}
@Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.network_usage_stats, container, false);
getActivity().getActionBar().setTitle(R.string.data_usage);
mPackageManager = getActivity().getPackageManager();
mNetstatsManager = (NetworkStatsManager)getActivity().getSystemService(
Context.NETWORK_STATS_SERVICE);
mListData = new ArrayList<>();
mListAdapter = new ArrayAdapter<List<NetworkStats.Bucket>>(getActivity(),
R.layout.data_usage_item, android.R.id.title, mListData) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View appView = convertView;
if (convertView == null) {
appView = inflater.inflate(R.layout.data_usage_item, parent, false);
final TextView title = (TextView) appView.findViewById(android.R.id.title);
final TextView summary = (TextView) appView.findViewById(android.R.id.summary);
final TextView state = (TextView) appView.findViewById(R.id.state);
ImageView imageView = (ImageView) appView.findViewById(android.R.id.icon);
appView.setTag(new ViewHolder(title, summary, state, imageView));
}
List<NetworkStats.Bucket> item = getItem(position);
bindView(appView, item);
return appView;
}
};
mQuerySpinner = (Spinner) view.findViewById(R.id.query_type_spinner);
mQuerySpinner.setOnItemSelectedListener(this);
mExplanation = (TextView) view.findViewById(R.id.explanation);
mStartDate = getTodayPlus(0, 0);
mEndDate = getTodayPlus(Calendar.DAY_OF_MONTH, 1);
mStartDateButton = (Button) view.findViewById(R.id.start_date_button);
if (mStartDateButton != null) {
mStartDateButton.setOnClickListener(this);
}
mEndDateButton = (Button) view.findViewById(R.id.end_date_button);
if (mEndDateButton != null) {
mEndDateButton.setOnClickListener(this);
}
updateButtonsText();
mDataUsageSummary = (TextView) view.findViewById(R.id.data_usage_summary);
mDataUsageList = (ListView) view.findViewById(android.R.id.list);
mDataUsageList.setAdapter(mListAdapter);
mAppHistoryList = (ListView) view.findViewById(R.id.app_history);
return view;
}