How to get Data usage on android by both wifi and Mobile data?

懵懂的女人 提交于 2020-01-07 05:35:11

问题


I need to get a data usage on each application installed on a android mobile.

Ex: I installed YouTube application on my mobile i need to get data usage of YouTube app by wifi and mobile data.

Excepted result:

YouTube - Wifi - 500MB.

YouTube - Mobile Data - 100 KB

I try to use TrafficStats API

int mobileTx = TrafficStats.getMobileTxBytes();
int mobileRx = TrafficStats.getMobileRxBytes();
int wifiTx = TrafficStats.getTotalTxBytes() - mobileTx;
int wifiRx = TrafficStats.getTotalRxBytes() - mobileRx;

the above give me the mobile entire data usage but i need to get per each application.


回答1:


TrafficStats.getUidRxBytes(int uid) and TrafficStats.getUidTxBytes(int uid) can help you out in this situation as these static methods provides info about bytes received and transmitted since last boot by some UID. for this you need to find UID of application for which you need detail. To find UID of application you can look into this thread - How to get uid value of an android application from a list displayed in a spinner?




回答2:


You can make use of getUidTxBytes API from TrafficStats class

long getUidTxBytes (int uid)
added in API level 8
Return number of bytes transmitted by the given UID since device boot. Counts packets across all network interfaces, and always increases monotonically since device boot. Statistics are measured at the network layer, so they include both TCP and UDP usage.
Before JELLY_BEAN_MR2, this may return UNSUPPORTED on devices where statistics aren't available.
Starting in N this will only report traffic statistics for the calling UID. It will return UNSUPPORTED for all other UIDs for privacy reasons. To access historical network statistics belonging to other UIDs, use NetworkStatsManager.

Although this also tells that you will have to make use of NetworkStatsManager to get network stats history of other than the calling apps.

Here uid is identifier of this process's uid



来源:https://stackoverflow.com/questions/43064647/how-to-get-data-usage-on-android-by-both-wifi-and-mobile-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!