getUidRxBytes和getUidTxBytes在Android 6.0中是不准确的,或者有时当我在Android 5.0中使用某个应用程序时

时间:2015-12-11 06:55:49

标签: android network-traffic

我的设备是nexus 6,当我使用getUidRxBytes和getUidTxBytes来获取某个特定应用程序的流量时。我发现getUidRxBytes + getUidTxBytes的结果比我使用的大。我只是听一首歌,getUidRxBytes + getUidTxBytes的结果是17MB。这不准确。我能知道为什么吗?谢谢....

1 个答案:

答案 0 :(得分:0)

各种应用程序在后台运行,定期消耗数据。我认为您应该看到特定应用程序消耗的数据,这可能是您的案例中的音乐应用程序。您需要使用TrafficStats.getUidRxBytes(UID)来获取应用程序使用的接收数据,因为TrafficStats.getUidRxBytes()可以为您提供上次重启时手机收到的总数据。首先获取要为其接收和传输数据的包名称。

 // handlers for getting traffic information
    private Handler mHandler = new Handler();
    private long mStartRX = 0;
    private long mStartTX = 0;
    int UID;

    @Override
        protected void onCreate(Bundle savedInstanceState) {

         //get a list of installed apps.
            final PackageManager pm = getPackageManager();

            List<ApplicationInfo> packages = pm.getInstalledApplications(
                    PackageManager.GET_META_DATA);

            for (ApplicationInfo packageInfo : packages) {
                if(packageInfo.packageName.equals("put your package name here")){

                    //get the UID for the selected app
                    UID = packageInfo.uid;
                    break; //found a match, don't need to search anymore
                } }


    // --------------- networking data related --------
    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 {
        //Function is called here to get the traffic data
        mHandler.postDelayed(mRunnable, 1000);
    }

} //的onCreate

将此代码放在onCreate()之外。这将每秒运行一次,并将显示logcat中以KB为单位的传输和接收数据的平均值。此外,您还可以打印使用的总KB值

private final Runnable mRunnable = new Runnable() {

    int count = 1;
    long received_data_kb_total;
    long received_data_kb_avg;

    long sent_data_kb_total;
    long sent_data_kb_avg;

    public void run() {

        received_data_kb_total = TrafficStats.getUidRxBytes(UID)/1024;
        received_data_kb_avg = received_data_kb_total/count;


        sent_data_kb_total = TrafficStats.getUidTxBytes(UID)/1024;
        sent_data_kb_avg = sent_data_kb_total/count;

        count += 1;

        Log.d("network", "avg received bytes are    :" + received_data_kb_avg + "Kb/s" );
        Log.d("network", "avg transmitted bytes are :" + sent_data_kb_avg + "Kb/s");


        mHandler.postDelayed(mRunnable, 1000);
    }
};

put your package name here替换为音乐应用的包名。