如何获得正确的字节数发送和接收TrafficStats? [英] How to get the correct number of bytes sent and received in TrafficStats?

查看:186
本文介绍了如何获得正确的字节数发送和接收TrafficStats?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序正在试图算多少字节的发送和接收通过WiFi /局域网和移动数据连接。为了做到这一点,我得到了 TrafficStats 计数器的值在一个时间点,并减去从下一次我检查。其值

  //获取计数器当前值
长currentMobileTxBytes = TrafficStats.getMobileTxBytes();
长currentMobileRxBytes = TrafficStats.getMobileRxBytes();
长totalTxBytes = TrafficStats.getTotalTxBytes();
长totalRxBytes = TrafficStats.getTotalRxBytes();

//获取移动数据计数,从目前的减去旧
长currentMobileSent = currentMobileTxBytes  -  oldMobileTxBytes;
长currentMobileReceived = currentMobileRxBytes  -  oldMobileRxBytes;

//得到的WiFi / LAN的数据统计,从移动减去总
长currentNetworkSent = totalTxBytes  -  currentMobileTxBytes;
长currentNetworkReceived = totalRxBytes  -  currentMobileRxBytes;
 

我觉得上面的算法是合理的,但是,我不知道如何检查这些计数器的准确性。例如,当我试图通过WiFi上传一个2.7MB的文件到Dropbox的,在 currentMobileSent 价值我是大约10MB。而且即使没有浏览网页,直到下一次检查,我得到的非零值,表明我确实收到了一些数据字节在等待期。

有没有办法对我来说,以检查 TrafficStats 到达这些数字?我知道,除了我的浏览器,有可能是在连接到互联网后台运行的其他应用程序,但2.7MB到10MB只是看起来像一个巨大的跳跃 - 我甚至获得90MB一次没有做任何事情。或者是有什么问题,我计算发送和接收的字节数的方法是什么?

解决方案

从<一个href="http://www.techrepublic.com/blog/software-engineer/create-a-network-monitor-using-androids-trafficstats-class/"相对=nofollow> TechRepublic的:

  

1,创建一个新的Eclipse中的Andr​​oid项目。记住使用TrafficStats类,你必须定位为Android 2.2(升级Froyo)的API或   高。

     

2.In的/ RES /布局文件夹中,我们将创建一个main.xml中的资源。对于这个项目,我们只是使用了一系列的文本视图在垂直   堆叠线性布局。

     

main.xml中

 &LT; XML版本=1.0编码=UTF-8&GT?;

    &LT; LinearLayout中的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android

     机器人:layout_width =FILL_PARENT

     机器人:layout_height =FILL_PARENT

     机器人:方向=垂直&GT;

     &LT;的TextView

     机器人:layout_width =FILL_PARENT

     机器人:layout_height =WRAP_CONTENT

     机器人:TEXTSIZE =16SP

     机器人:TEXTSTYLE =黑体

     机器人:重力=中心

     机器人:paddingBottom会=20dip

     机器人:文本=流量统计演示/&GT;

     &LT;的TextView

     机器人:layout_width =FILL_PARENT

     机器人:layout_height =WRAP_CONTENT

     机器人:TEXTSIZE =14sp

     机器人:文字颜色=#00FF00

     机器人:重力=中心

     机器人:文=发送字节/&GT;

     &LT;的TextView

     机器人:layout_width =FILL_PARENT

     机器人:layout_height =WRAP_CONTENT

     机器人:TEXTSIZE =14sp

     机器人:重力=中心

     机器人:文本=0

     机器人:ID =@ + ID / TX/&GT;

    &LT;的TextView

    机器人:layout_width =FILL_PARENT

    机器人:layout_height =WRAP_CONTENT

    机器人:TEXTSIZE =14sp

    机器人:文字颜色=#FF0000

    机器人:重力=中心

    机器人:文本=接收字节/&GT;

    &LT;的TextView

    机器人:layout_width =FILL_PARENT

    机器人:layout_height =WRAP_CONTENT

    机器人:TEXTSIZE =14sp

    机器人:重力=中心

    机器人:文本=0

    机器人:ID =@ + ID / RX/&GT;

    &LT; / LinearLayout中&GT;
 

使用我们的场所布局,我们可以移动到/ src文件夹。创建   Main.java通过扩展Activity类。让我们再继续前进,   声明了三个私有类变量。

     

Main.java

 包com.authorwjf;

 进口android.app.Activity;

 进口android.app.AlertDialog;

 进口android.net.TrafficStats;

 进口android.os.Bundle;

 进口android.os.Handler;

 进口android.widget.TextView;

 公共类主要扩展活动{

 私人处理程序mHandler =新的处理程序();

 私人长mStartRX = 0;

 私人长mStartTX = 0;

  }
 

我们将使用上创建覆盖初始化我们的私人   变量,以及安排在UI线程上的回调。做一个   注意检查枚举TrafficStats.UNSUPPORTED的。虽然我的   与TrafficStats一流的经验已经顺利时,   谷歌官方文件指出,一些设备可能不支持   这种类型的报告,当情况是这样的调用返回   上述数值。出于这个原因,它是写一个好主意,你的   code防守,因为我在这里展示。

     

Main.java

  @覆盖

     公共无效的onCreate(包savedInstanceState){

     super.onCreate(savedInstanceState);

     的setContentView(R.layout.main);

     mStartRX = TrafficStats.getTotalRxBytes();

     mStartTX = TrafficStats.getTotalTxBytes();

     如果(mStartRX == TrafficStats.UNSUPPORTED || mStartTX == TrafficStats.UNSUPPORTED){

      AlertDialog.Builder警报=新AlertDialog.Builder(本);

      alert.setTitle(呃哦!);

     alert.setMessage(您的设备不支持流量统计监测。);

     alert.show();

     } 其他 {

     mHandler.postDelayed(mRunnable,1000);

     }

       }
 

     

最后但并非最不重要的,我们需要更新我们的显示和重新安排   可运行。

     

Main.java

 私人最终可运行mRunnable =新的Runnable(){

      公共无效的run(){

      TextView的RX =(TextView中)findViewById(R.id.RX);

       TextView的TX =(TextView中)findViewById(R.id.TX);

       长RXBYTES = TrafficStats.getTotalRxBytes() -  mStartRX;

         RX.setText(Long.toString(RXBYTES));

       长TXBYTES = TrafficStats.getTotalTxBytes() -  mStartTX;

       TX.setText(Long.toString(TXBYTES));

        mHandler.postDelayed(mRunnable,1000);

           }

           };
 

My app is trying to count the number of bytes send and received over WiFi/LAN and mobile data connections. To do that, I get the values of TrafficStats counters at one point in time and subtract that from its values the next time I check.

// get current values of counters
long currentMobileTxBytes = TrafficStats.getMobileTxBytes();
long currentMobileRxBytes = TrafficStats.getMobileRxBytes();
long totalTxBytes = TrafficStats.getTotalTxBytes();
long totalRxBytes = TrafficStats.getTotalRxBytes();

// to get mobile data count, subtract old from current
long currentMobileSent = currentMobileTxBytes - oldMobileTxBytes;
long currentMobileReceived = currentMobileRxBytes - oldMobileRxBytes;

// to get WiFi/LAN data count, subtract total from mobile
long currentNetworkSent = totalTxBytes - currentMobileTxBytes;
long currentNetworkReceived = totalRxBytes - currentMobileRxBytes;

I feel that the above algorithm is reasonable, however, I'm not sure how to check the accuracy of these counters. For example, when I tried uploading a 2.7MB file to Dropbox via WiFi, the currentMobileSent value I got was around 10MB. And even without surfing the web until the next check, I get non-zero values indicating that I did receive some bytes of data over the waiting period.

Is there a way for me to check how TrafficStats arrives at these numbers? I'm aware that besides my browser, there might be other applications running in the background that connect to the internet, but 2.7MB to 10MB just seems like a huge jump--I even "received" 90MB once without doing anything. Or is there something wrong with the way I'm computing the bytes sent and received?

解决方案

From TechRepublic:

1.Create a new Android project in Eclipse. Remember to use the TrafficStats class you must target the API for Android 2.2 (Froyo) or higher.

2.In the /res/layout folder we will create a main.xml resource. For this project, we are just using a series of text views in a vertically stacked linear layout.

main.xml

     <?xml version="1.0" encoding="utf-8"?>

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

     android:layout_width="fill_parent"

     android:layout_height="fill_parent"

     android:orientation="vertical" >

     <TextView

     android:layout_width="fill_parent"

     android:layout_height="wrap_content"

     android:textSize="16sp"

     android:textStyle="bold"

     android:gravity="center"

     android:paddingBottom="20dip"

     android:text="Traffic Stats Demo" />

     <TextView

     android:layout_width="fill_parent"

     android:layout_height="wrap_content"

     android:textSize="14sp"

     android:textColor="#00ff00"

     android:gravity="center"

     android:text="Transmit Bytes" />

     <TextView

     android:layout_width="fill_parent"

     android:layout_height="wrap_content"

     android:textSize="14sp"

     android:gravity="center"

     android:text="0"

     android:id="@+id/TX"/>

    <TextView

    android:layout_width="fill_parent"

    android:layout_height="wrap_content"

    android:textSize="14sp"

    android:textColor="#ff0000"

    android:gravity="center"

    android:text="Receive Bytes" />

    <TextView

    android:layout_width="fill_parent"

    android:layout_height="wrap_content"

    android:textSize="14sp"

    android:gravity="center"

    android:text="0"

    android:id="@+id/RX"/>

    </LinearLayout>

With our layout in place we can move on to the /src folder. Create Main.java by extending the Activity class. Let’s also go ahead and declare three private class variables.

Main.java

 package com.authorwjf;

 import android.app.Activity;

 import android.app.AlertDialog;

 import android.net.TrafficStats;

 import android.os.Bundle;

 import android.os.Handler;

 import android.widget.TextView;

 public class Main extends Activity {

 private Handler mHandler = new Handler();

 private long mStartRX = 0;

 private long mStartTX = 0;

  }

We will use the on create override to initialize our private variables, as well as schedule a callback on the UI thread. Make a note of the check for the enum TrafficStats.UNSUPPORTED. While my experience with the TrafficStats class has been without a hitch, the official Google documentation states that some devices may not support this type of reporting and when that is the case the call returns the aforementioned value. For that reason it’s a good idea to write your code defensively, as I’ve demonstrated here.

Main.java

     @Override

     public void onCreate(Bundle savedInstanceState) {

     super.onCreate(savedInstanceState);

     setContentView(R.layout.main);

     mStartRX = TrafficStats.getTotalRxBytes();

     mStartTX = TrafficStats.getTotalTxBytes();

     if (mStartRX == TrafficStats.UNSUPPORTED || mStartTX ==     TrafficStats.UNSUPPORTED) {

      AlertDialog.Builder alert = new AlertDialog.Builder(this);

      alert.setTitle("Uh Oh!");

     alert.setMessage("Your device does not support traffic stat monitoring.");

     alert.show();

     } else {

     mHandler.postDelayed(mRunnable, 1000);

     }

       }

Last but not least we need to update our display and reschedule the runnable.

Main.java

      private final Runnable mRunnable = new Runnable() {

      public void run() {

      TextView RX = (TextView)findViewById(R.id.RX);

       TextView TX = (TextView)findViewById(R.id.TX);

       long rxBytes = TrafficStats.getTotalRxBytes()- mStartRX;

         RX.setText(Long.toString(rxBytes));

       long txBytes = TrafficStats.getTotalTxBytes()- mStartTX;

       TX.setText(Long.toString(txBytes));

        mHandler.postDelayed(mRunnable, 1000);

           }

           };

这篇关于如何获得正确的字节数发送和接收TrafficStats?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆