下面列出了android.net.TrafficStats#getTotalTxBytes ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static float getTxAll()
{
long currentTx = TrafficStats.getTotalTxBytes();
if(startTx == 0) {
startTx = currentTx;
}
long speed = currentTx - startTx;
if (triggerReload) {
startTx = currentTx;
triggerReload = false;
}
return speed / 1024F;
}
public static float getTxTotal()
{
long currentTime = System.currentTimeMillis();
long currentTx = TrafficStats.getTotalTxBytes();
if (lastTxTime == 0 || lastTx == 0)
{
lastTxTime = currentTime;
lastTx = currentTx;
return 0;
}
float speed = (currentTx - lastTx) / (float)(currentTime - lastTxTime);
lastTx = currentTx;
lastTxTime = currentTime;
return speed;
}
/**
* init data
*/
@Override
protected void initData() {
long totalRxBytes = TrafficStats.getTotalRxBytes();
long totalTxBytes = TrafficStats.getTotalTxBytes();
long mobileRxBytes = TrafficStats.getMobileRxBytes();
long mobileTxBytes = TrafficStats.getMobileTxBytes();
long totalBytes = totalRxBytes + totalTxBytes;
long mobileBytes = mobileRxBytes + mobileTxBytes;
tvTotalTrafficStatsSum.setText(getString(R.string.total_traffic_stats_sum, Formatter.formatFileSize(this, totalBytes)));
tvMobileTrafficStatsSum.setText(getString(R.string.mobile_traffic_stats_sum, Formatter.formatFileSize(this, mobileBytes)));
tvTotalTrafficStats.setText(getString(R.string.traffic_stats_upload_download, Formatter.formatFileSize(this, totalTxBytes), Formatter.formatFileSize(this, totalRxBytes)));
tvMobileTrafficStats.setText(getString(R.string.traffic_stats_upload_download, Formatter.formatFileSize(this, mobileTxBytes), Formatter.formatFileSize(this, mobileRxBytes)));
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvSupported = (TextView) findViewById(R.id.tvSupported);
tvDataUsageWiFi = (TextView) findViewById(R.id.tvDataUsageWiFi);
tvDataUsageMobile = (TextView) findViewById(R.id.tvDataUsageMobile);
tvDataUsageTotal = (TextView) findViewById(R.id.tvDataUsageTotal);
if (TrafficStats.getTotalRxBytes() != TrafficStats.UNSUPPORTED && TrafficStats.getTotalTxBytes() != TrafficStats.UNSUPPORTED) {
handler.postDelayed(runnable, 0);
initAdapter();
lvApplications = (ListView) findViewById(R.id.lvInstallApplication);
lvApplications.setAdapter(adapterApplications);
} else {
tvSupported.setVisibility(View.VISIBLE);
}
}
private void update_labels() {
if (totalOn) {
long totalRxBytes = TrafficStats.getTotalRxBytes();
long totalTxBytes = TrafficStats.getTotalTxBytes();
totalTransferTV.setText(String.format("Total:↓%s, ↑%s, ⇅%s", //↑↓▲▼⬆⬇⬍
Formatter.formatFileSize(activity, totalRxBytes),// + "@" + rxRate + unitTypeArr[unitType],
Formatter.formatFileSize(activity, totalTxBytes),// + "@" + txRate + unitTypeArr[unitType],
Formatter.formatFileSize(activity, totalRxBytes + totalTxBytes)// + "@" + totalRate + unitTypeArr[unitType],
));
} else {
long rxRate = totalRxSincePrev * 1000000 / (prevElapsedTime / 1000);
long txRate = totalTxSincePrev * 1000000 / (prevElapsedTime / 1000);
long totalRate = (totalRxSincePrev + totalTxSincePrev) * 1000000 / (prevElapsedTime / 1000);
if (unitType > 3) {
rxRate = (rxRate >> (10 * (unitType - 4)));
txRate = (txRate >> (10 * (unitType - 4)));
totalRate = (totalRate >> (10 * (unitType - 4)));
} else {
rxRate = ((rxRate >> (10 * unitType)) << 3);
txRate = ((txRate >> (10 * unitType)) << 3);
totalRate = ((totalRate >> (10 * unitType)) << 3);
}
totalTransferTV.setText(String.format("Current:↓%s, ↑%s, ⇅%s", //↑↓▲▼⬆⬇⬍
Formatter.formatFileSize(activity, totalRxSincePrev) + "@" + rxRate + unitTypeArr[unitType],
Formatter.formatFileSize(activity, totalTxSincePrev) + "@" + txRate + unitTypeArr[unitType],
Formatter.formatFileSize(activity, totalRxSincePrev + totalTxSincePrev) + "@" + totalRate + unitTypeArr[unitType]
));
}
selectionStatusTV.setText(myChecked.size() + "/" + appStatsList.size());
}
@Override
public void stop() {
if (running) {
running = false;
trafficTxEnd = TrafficStats.getTotalTxBytes();
trafficRxEnd = TrafficStats.getTotalRxBytes();
}
}
@Override
public void run() {
while (true) {
if (reqStop) {
if (callback != null) {
callback.afterStop();
}
return;
}
if (lastTotalTxBytes == TrafficStats.UNSUPPORTED) {
lastTotalTxBytes = TrafficStats.getTotalTxBytes();
lastTotalRxBytes = TrafficStats.getTotalRxBytes();
lastTotalBytes = lastTotalTxBytes + lastTotalRxBytes;
SystemClock.sleep(refreshPeriod);
continue;
}
long total = TrafficStats.getTotalTxBytes();
netSpeedUp = (int) ((total - lastTotalTxBytes) * 1000 / refreshPeriod);
lastTotalTxBytes = total;
total = TrafficStats.getTotalRxBytes();
netSpeedDown = (int) ((total - lastTotalRxBytes) * 1000 / refreshPeriod);
lastTotalRxBytes = total;
total = lastTotalTxBytes + lastTotalRxBytes;
netSpeed = (int) ((total - lastTotalBytes) * 1000 / refreshPeriod);
// recentBytes[(++recentIndex) % recentBytes.length] = (int) (total - lastTotalBytes);
lastTotalBytes = total;
usedBytes = lastTotalBytes - startTotalBytes;
if (callback != null) {
callback.onUpdate(netSpeed, netSpeedUp, netSpeedDown, usedBytes);
}
SystemClock.sleep(refreshPeriod);
}
}
@Override
protected void initView()
{
setActionBarTitle(R.string.traffic_statistics);
TrafficStats.getTotalTxBytes();
}
/**
* {@inheritDoc}
*/
@Override
public long getWiFiTxBytes() throws IOException {
final long l = TrafficStats.getMobileTxBytes();
final long la = TrafficStats.getTotalTxBytes();
if (la < 0L || la < l) {
return 0L;
}
return la - l;
}
@Override
public int start() {
if ((trafficRxStart = TrafficStats.getTotalRxBytes()) == TrafficStats.UNSUPPORTED) {
return SERVICE_NOT_SUPPORTED;
}
running = true;
trafficTxStart = TrafficStats.getTotalTxBytes();
return SERVICE_START_OK;
}
public void run() {
long mobile = TrafficStats.getMobileRxBytes() + TrafficStats.getMobileTxBytes();
long total = TrafficStats.getTotalRxBytes() + TrafficStats.getTotalTxBytes();
tvDataUsageWiFi.setText("" + (total - mobile) / 1024 + " Kb");
tvDataUsageMobile.setText("" + mobile / 1024 + " Kb");
tvDataUsageTotal.setText("" + total / 1024 + " Kb");
if (dataUsageTotalLast != total) {
dataUsageTotalLast = total;
updateAdapter();
}
handler.postDelayed(runnable, 5000);
}
@Override
public long getTotalTxBytes() {
return TrafficStats.getTotalTxBytes();
}
/**
* @return Number of bytes transmitted 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.
*/
@CalledByNative
private static long getTotalTxBytes() {
long bytes = TrafficStats.getTotalTxBytes();
return bytes != TrafficStats.UNSUPPORTED ? bytes : TrafficStatsError.ERROR_NOT_SUPPORTED;
}
public void updateViewData() {
long tempSum = TrafficStats.getTotalRxBytes()
+ TrafficStats.getTotalTxBytes();
long rxtxLast = tempSum - rxtxTotal;
double totalSpeed = rxtxLast * 1000 / TIME_SPAN;
rxtxTotal = tempSum;
long tempMobileRx = TrafficStats.getMobileRxBytes();
long tempMobileTx = TrafficStats.getMobileTxBytes();
long tempWlanRx = TrafficStats.getTotalRxBytes() - tempMobileRx;
long tempWlanTx = TrafficStats.getTotalTxBytes() - tempMobileTx;
long mobileLastRecv = tempMobileRx - mobileRecvSum;
long mobileLastSend = tempMobileTx - mobileSendSum;
long wlanLastRecv = tempWlanRx - wlanRecvSum;
long wlanLastSend = tempWlanTx - wlanSendSum;
double mobileRecvSpeed = mobileLastRecv * 1000 / TIME_SPAN;
double mobileSendSpeed = mobileLastSend * 1000 / TIME_SPAN;
double wlanRecvSpeed = wlanLastRecv * 1000 / TIME_SPAN;
double wlanSendSpeed = wlanLastSend * 1000 / TIME_SPAN;
mobileRecvSum = tempMobileRx;
mobileSendSum = tempMobileTx;
wlanRecvSum = tempWlanRx;
wlanSendSum = tempWlanTx;
//==========================================================
if (isMulti) {
if (mobileRecvSpeed >= 0d) {
tvMobileRx.setText(showSpeed(mobileRecvSpeed));
}
if (mobileSendSpeed >= 0d) {
tvMobileTx.setText(showSpeed(mobileSendSpeed));
}
if (wlanRecvSpeed >= 0d) {
tvWlanRx.setText(showSpeed(wlanRecvSpeed));
}
if (wlanSendSpeed >= 0d) {
tvWlanTx.setText(showSpeed(wlanSendSpeed));
}
} else {
//==============================================================
if (totalSpeed >= 0d) {
tvSum.setText(showSpeed(totalSpeed));
}
}
//==============================================================
}
private static long[] getTotalRxTxBytesFromStats() {
return new long[]{TrafficStats.getTotalRxBytes(),
TrafficStats.getTotalTxBytes()};
}
public void setStartTotalBytes(long startTotalBytes) {
if (startTotalBytes < TrafficStats.getTotalRxBytes() + TrafficStats.getTotalTxBytes()) {
this.startTotalBytes = startTotalBytes;
}
}
public void resetUsedBytes() {
startTotalBytes = TrafficStats.getTotalRxBytes() + TrafficStats.getTotalTxBytes();
}
/**
* @return Number of bytes transmitted 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.
*/
@CalledByNative
private static long getTotalTxBytes() {
long bytes = TrafficStats.getTotalTxBytes();
return bytes != TrafficStats.UNSUPPORTED ? bytes : TrafficStatsError.ERROR_NOT_SUPPORTED;
}
/**
* called by the timer and return the current context info of device
*
* @return a hash map that contains all the context data
*/
@SuppressLint("NewApi")
private HashMap<String, String> getCurrentContextInfo() {
HashMap<String, String> currentContext = new HashMap<String, String>();;
long intervalPktSend = 0;
long intervalPktRecv = 0;
long intervalSend = 0;
long intervalRecv = 0;
long sendBytes = TrafficStats.getTotalTxBytes();
long recvBytes = TrafficStats.getTotalRxBytes();
long sendPkt = TrafficStats.getTotalTxPackets();
long recvPkt = TrafficStats.getTotalRxPackets();
if (prevSend != -1 && prevRecv != -1) {
intervalSend = sendBytes - prevSend;
intervalRecv = recvBytes - prevRecv;
}
if (prevPktSend != -1 && prevPktRecv != -1) {
intervalPktSend = sendPkt - prevPktSend;
intervalPktRecv = recvPkt - prevPktRecv;
}
// we only return the context info if (1) it's the first time it gets called (2) we have
// change in the amount of packet/byte sent/received.
if (prevSend == -1 || prevRecv == -1 || prevPktSend == -1 || prevPktRecv == -1
|| intervalSend != 0 || intervalRecv != 0 || intervalPktSend != 0 || intervalPktRecv != 0) {
currentContext.put("timestamp", (System.currentTimeMillis() * 1000) + "");
// currentContext.put("rssi", phoneUtils.getCurrentRssi() + "");
currentContext.put("inc_total_bytes_send", intervalSend + "");
currentContext.put("inc_total_bytes_recv", intervalRecv + "");
currentContext.put("inc_total_pkt_send", intervalPktSend + "");
currentContext.put("inc_total_pkt_recv", intervalPktRecv + "");
currentContext.put("battery_level", phoneUtils.getCurrentBatteryLevel() + "");
}
prevSend = sendBytes;
prevRecv = recvBytes;
prevPktSend = sendPkt;
prevPktRecv = recvPkt;
return currentContext;
}
/**
* 获取当前上传流量总和
*
* @return
*/
public static long getNetworkTxBytes() {
return TrafficStats.getTotalTxBytes();
}