下面列出了android.net.TrafficStats#getUidRxBytes ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 计算当前流量
*
* @param context Context
* @param tag traffic tag
* @return received bytes
*/
public static long current(Context context, String tag) {
Long appRxValue = sReceivedBytes.get(tag);
Long appTxValue = sSendBytes.get(tag);
if (appRxValue == null || appTxValue == null) {
if (DEBUG) {
LogUtils.w(TAG, "current() appRxValue or appTxValue is null.");
}
return 0;
}
final int uid = getUid(context);
long appRxValue2 = TrafficStats.getUidRxBytes(uid);
long appTxValue2 = TrafficStats.getUidTxBytes(uid);
long rxValue = appRxValue2 - appRxValue;
long txValue = appTxValue2 - appTxValue;
if (DEBUG) {
LogUtils.v(TAG, "current() rxValue=" + rxValue / 1000 + " txValue=" + txValue / 1000 + " uid=" + uid);
}
return rxValue;
}
@VisibleToAvoidSynthetics
synchronized void updateTotalBytes() {
long currentTotalTxBytes = TrafficStats.getUidTxBytes(UID);
long currentTotalRxBytes = TrafficStats.getUidRxBytes(UID);
if (currentTotalRxBytes == TrafficStats.UNSUPPORTED
|| currentTotalTxBytes == TrafficStats.UNSUPPORTED) {
mIsValid = false;
return;
}
int prefix = mCurrentNetworkType == TYPE_WIFI ? WIFI : MOBILE;
long lastTotalTxBytes = mTotalBytes[TX | MOBILE] + mTotalBytes[TX | WIFI];
long lastTotalRxBytes = mTotalBytes[RX | MOBILE] + mTotalBytes[RX | WIFI];
mTotalBytes[TX | prefix] += currentTotalTxBytes - lastTotalTxBytes;
mTotalBytes[RX | prefix] += currentTotalRxBytes - lastTotalRxBytes;
}
/**
* 统计TAG流量
*
* @param context Context
* @param tag traffic tag
* @return received bytes
*/
public static long stop(Context context, String tag) {
Long appRxValue = sReceivedBytes.remove(tag);
Long appTxValue = sSendBytes.remove(tag);
if (appRxValue == null || appTxValue == null) {
if (DEBUG) {
LogUtils.w(TAG, "stop() appRxValue or appTxValue is null.");
}
return 0;
}
final int uid = getUid(context);
long appRxValue2 = TrafficStats.getUidRxBytes(uid);
long appTxValue2 = TrafficStats.getUidTxBytes(uid);
long rxValue = appRxValue2 - appRxValue;
long txValue = appTxValue2 - appTxValue;
if (DEBUG) {
LogUtils.v(TAG, "stop() rxValue=" + rxValue / 1000 + " txValue=" + txValue / 1000 + " uid=" + uid);
}
return rxValue;
}
private long getNetSpeed(Context context) {
if (context == null) {
return 0;
}
long nowTotalRxBytes = TrafficStats.getUidRxBytes(context.getApplicationInfo().uid) == TrafficStats.UNSUPPORTED ? 0 : (TrafficStats.getTotalRxBytes() / 1024);//转为KB
long nowTimeStamp = System.currentTimeMillis();
long calculationTime = (nowTimeStamp - lastTimeStamp);
if (calculationTime == 0) {
return calculationTime;
}
//毫秒转换
long speed = ((nowTotalRxBytes - lastTotalRxBytes) * 1000 / calculationTime);
lastTimeStamp = nowTimeStamp;
lastTotalRxBytes = nowTotalRxBytes;
return speed;
}
private long getNetSpeed(Context context) {
if (context == null) {
return 0;
}
long nowTotalRxBytes = TrafficStats.getUidRxBytes(context.getApplicationInfo().uid) == TrafficStats.UNSUPPORTED ? 0 : (TrafficStats.getTotalRxBytes() / 1024);//转为KB
long nowTimeStamp = System.currentTimeMillis();
long calculationTime = (nowTimeStamp - lastTimeStamp);
if (calculationTime == 0) {
return calculationTime;
}
//毫秒转换
long speed = ((nowTotalRxBytes - lastTotalRxBytes) * 1000 / calculationTime);
lastTimeStamp = nowTimeStamp;
lastTotalRxBytes = nowTotalRxBytes;
return speed;
}
@SuppressLint("SetTextI18n")
private void updateData() {
if (App.ClementineConnection == null) {
return;
}
long diff = new Date().getTime() - App.ClementineConnection.getStartTime();
String dateFormat = String.format(Locale.US, "%02d:%02d:%02d",
TimeUnit.MILLISECONDS.toHours(diff),
TimeUnit.MILLISECONDS.toMinutes(diff) % 60,
TimeUnit.MILLISECONDS.toSeconds(diff) % 60
);
tv_time.setText(dateFormat);
int uid = getActivity().getApplicationInfo().uid;
if (TrafficStats.getUidRxBytes(uid) == TrafficStats.UNSUPPORTED) {
tv_traffic.setText(R.string.connection_traffic_unsupported);
} else {
String tx = Utilities.humanReadableBytes(
TrafficStats.getUidTxBytes(uid) - App.ClementineConnection.getStartTx(), true);
String rx = Utilities.humanReadableBytes(
TrafficStats.getUidRxBytes(uid) - App.ClementineConnection.getStartRx(), true);
long total = TrafficStats.getUidTxBytes(uid) - App.ClementineConnection.getStartTx() +
TrafficStats.getUidRxBytes(uid) - App.ClementineConnection.getStartRx();
if (TimeUnit.MILLISECONDS.toSeconds(diff) != 0) {
long a = total / TimeUnit.MILLISECONDS.toSeconds(diff);
String perSecond = Utilities.humanReadableBytes(a, true);
tv_traffic.setText(tx + " / " + rx + " (" + perSecond + "/s)");
}
}
}
@Override
public int start() {
uid = Process.myUid();
if ((trafficRxStart = TrafficStats.getUidRxBytes(uid)) == TrafficStats.UNSUPPORTED) {
return SERVICE_NOT_SUPPORTED;
}
running = true;
trafficTxStart = TrafficStats.getUidTxBytes(uid);
return SERVICE_START_OK;
}
public static long getIncomingNetworkUsage(@NonNull final Context context) {
// Get running processes
ActivityManager manager = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
if (null == manager) return -1;
long totalReceived = 0;
List<ActivityManager.RunningAppProcessInfo> runningApps = manager.getRunningAppProcesses();
if (runningApps != null)
for (ActivityManager.RunningAppProcessInfo runningApp : runningApps) {
long received = TrafficStats.getUidRxBytes(runningApp.uid);
totalReceived += received;
}
return totalReceived;
}
public NetUtil(int uid) {
mUid = uid;
mBeginTotalTxBytes = TrafficStats.getUidTxBytes(mUid);
mBeginTotalRxBytes = TrafficStats.getUidRxBytes(mUid);
mLastTotalTxBytes = TrafficStats.getUidTxBytes(mUid);
mLastTotalRxBytes = TrafficStats.getUidRxBytes(mUid);
}
/**
* 流量差(接收)
* 和上一次获取的时候相比
*
* @return
*/
public double getDiffRxBytes() {
long currentRx = TrafficStats.getUidRxBytes(mUid);
long diff;
diff = currentRx - mLastTotalRxBytes;
mLastTotalRxBytes = currentRx;
return diff;
}
public void resetAppTraffic() {
final List<AppTraffic> list = trafficDbService.getAppTrafficList();
AppTraffic appTraffic = null;
for (int i = 0; i < list.size(); i++) {
appTraffic = list.get(i);
appTraffic.totalRx = TrafficStats.getUidRxBytes(appTraffic.uid);
appTraffic.totalTx = TrafficStats.getUidTxBytes(appTraffic.uid);
trafficDbService.saveAppTraffic(appTraffic);
}
}
private void waitForNetworkUpdate(long idleTimeoutMillis, long globalTimeoutMillis) {
final long startTimeMillis = SystemClock.uptimeMillis();
long prevTraffic = TrafficStats.getUidTxBytes(uid) + TrafficStats.getUidRxBytes(uid);
boolean idleDetected = false;
long totTraffic = 0;
while (!idleDetected) {
final long elapsedTimeMillis = SystemClock.uptimeMillis() - startTimeMillis;
final long remainingTimeMillis = globalTimeoutMillis - elapsedTimeMillis;
if (remainingTimeMillis <= 0) {
Util.err("NO_IDLE_TIMEOUT: " + globalTimeoutMillis);
break;
}
try {
Thread.sleep(idleTimeoutMillis);
long currTraffic = TrafficStats.getUidTxBytes(uid) + TrafficStats.getUidRxBytes(uid);
long delta = currTraffic - prevTraffic;
if (delta > 0) {
totTraffic += delta;
prevTraffic = currTraffic;
} else { // idle detected
idleDetected = true;
}
} catch (InterruptedException ie) {
/* ignore */
}
}
if (idleDetected) {
Util.log("Traffic: " + totTraffic);
}
}
@Test
public void getUidRxBytes() throws Exception {
double val = TrafficSampler.getUidRxBytes(1);
assertEquals(val,100,0);
PowerMockito.verifyStatic(times(2));
TrafficStats.getUidRxBytes(1);
}
public static double getDataReceived() {
return (double) TrafficStats.getUidRxBytes(android.os.Process
.myUid()) / (1024 * 1024);
}
private long[] getFlowByAPI(int uid) {
long flowUpload = TrafficStats.getUidTxBytes(uid);
long flowDownload = TrafficStats.getUidRxBytes(uid);
return new long[]{flowUpload, flowDownload};
}
private long getTotalRxBytes() {
return TrafficStats.getUidRxBytes(mContext.getApplicationInfo().uid)==TrafficStats.UNSUPPORTED ? 0 :(TrafficStats.getTotalRxBytes()/1024);//转为KB
}
@Override
public long getBytesReceived() {
return TrafficStats.getUidRxBytes(uid);
}
public static double getUidRxBytes(int uid) {
return TrafficStats.getUidRxBytes(uid) == TrafficStats.UNSUPPORTED ? 0 : TrafficStats.getUidRxBytes(uid);
}
/**
* @return Number of bytes received since device boot that were attributed to caller's UID.
* 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.
*/
@CalledByNative
private static long getCurrentUidRxBytes() {
long bytes = TrafficStats.getUidRxBytes(Process.myUid());
return bytes != TrafficStats.UNSUPPORTED ? bytes : TrafficStatsError.ERROR_NOT_SUPPORTED;
}
/**
* 本次所消耗的流量(接收)
*
* @return
*/
public double getTotalRxBytes() {
long currentRx = TrafficStats.getUidRxBytes(mUid);
return currentRx - mBeginTotalRxBytes;
}