android.app.usage.NetworkStatsManager Java Examples

The following examples show how to use android.app.usage.NetworkStatsManager. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MultipathPolicyTracker.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #2
Source File: NetworkStatsService.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #3
Source File: NetworkStatsObservers.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #4
Source File: NetworkStatsService.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example #5
Source File: NetworkStatsObservers.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
@Override
public void binderDied() {
    if (LOGV) Slog.v(TAG, "RequestInfo binderDied("
            + mRequest + ", " + mBinder + ")");
    mStatsObserver.unregister(mRequest, Process.SYSTEM_UID);
    callCallback(NetworkStatsManager.CALLBACK_RELEASED);
}
 
Example #6
Source File: NetworkStatsObservers.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example #7
Source File: NetworkStatsObservers.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private String callbackTypeToName(int callbackType) {
    switch (callbackType) {
        case NetworkStatsManager.CALLBACK_LIMIT_REACHED:
            return "LIMIT_REACHED";
        case NetworkStatsManager.CALLBACK_RELEASED:
            return "RELEASED";
        default:
            return "UNKNOWN";
    }
}
 
Example #8
Source File: NetUtils.java    From Awesome-WanAndroid with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example #9
Source File: DataManager.java    From AppsMonitor with MIT License 5 votes vote down vote up
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;
}
 
Example #10
Source File: MultipathPolicyTracker.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
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();
    }
}
 
Example #11
Source File: NetworkStatsService.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
@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);
}
 
Example #12
Source File: SystemServiceRegistry.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
@Override
public NetworkStatsManager createService(ContextImpl ctx) throws ServiceNotFoundException {
    return new NetworkStatsManager(ctx.getOuterContext());
}
 
Example #13
Source File: ServiceUtil.java    From PowerFileExplorer with GNU General Public License v3.0 4 votes vote down vote up
@TargetApi(23)
public static NetworkStatsManager getNetworkStatsManager() {
    return (NetworkStatsManager) getSystemService(Context.NETWORK_STATS_SERVICE);
}
 
Example #14
Source File: NetUtilAboveM.java    From StickyDecoration with Apache License 2.0 4 votes vote down vote up
@TargetApi(Build.VERSION_CODES.M)
public NetUtilAboveM(Context context) {
    NetworkStatsManager networkStatsManager = (NetworkStatsManager) context.getSystemService(context.NETWORK_STATS_SERVICE);
}
 
Example #15
Source File: NetworkStatsManagerBytesCollector.java    From Battery-Metrics with MIT License 4 votes vote down vote up
public NetworkStatsManagerBytesCollector(Context context) {
  mNetworkStatsManager = context.getSystemService(NetworkStatsManager.class);
  mStartTime = Long.MIN_VALUE;
}
 
Example #16
Source File: NetworkUsageStatsFragment.java    From android-testdpc with Apache License 2.0 4 votes vote down vote up
@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;
}