天天看点

Android中TrafficStats流量监控类

这个类提供了网络流量统计,这个统计包括上传和下载的字节数和网络数据包数。需要注意的是这个统计不能在所有的平台上使用,如果设备不支持的话,就会返回UNSUPPORTED。

常用函数:

public static void setThreadStatsTag(int tag)

public static int getThreadStatsTag()

public static void clearThreadStatsTag()

public static void tagSocket(Socket socket)

public static void untagSocket(Socket socket)
           

在android 4.0.4的sdk DDMS中,有了一个工具:Network Traffic Tool 。通过这个工具可以实时地监测网络的使用情况,使程序员更好的发现自己的应用程序在什么时候发送接收了多少的网络数据.

如果要更加清楚地看清每一个网络连接的使用情况可以在程序中对网络连接打tag,如对socket连接可以这样:

TrafficStats.setThreadStatsTag();
TrafficStats.tagSocket(outputSocket);
// Transfer data using socket
TrafficStats.untagSocket(outputSocket);
           

对于Apache HttpClient and URLConnection 会自动打上tag,所以只要设置上tag名就可以了:

对于Apache HttpClient and URLConnection 会自动打上tag,所以只要设置上tag名就可以了:

TrafficStats.setThreadStatsTag();
try {
  // Make network request using HttpClient.execute()
} finally {
  TrafficStats.clearThreadStatsTag();
}
           

其他函数:

public static void incrementOperationCount(int operationCount)

public static void incrementOperationCount(int tag, int operationCount)
           

增加网络操作的数量

public static long getMobileTxPackets()   通过流量发送的数据包数

public static long getMobileRxPackets() 通过流量接收到的数据包数

public static long getMobileTxBytes()  通过流量发送的字节数

public static long getMobileRxBytes()  通过流量接收的字节数

public static long getTotalTxPackets()  发送的数据包总数,包括流量和WIFI

public static long getTotalRxPackets()  接收的数据包总数,包括流量和WIFI

public static long getTotalTxBytes()  发送的字节总数,包括流量和WIFI

public static long getTotalRxBytes()  接收的字节总数,包括流量和WIFI

public static long getUidTxPackets(int uid) 获取指定网络UID发送的数据包数

public static long getUidRxPackets(int uid)  获取指定网络UID接收的数据包数

public static long getUidTxBytes(int uid)  获取指定网络UID发送的字节数

public static long getUidRxBytes(int uid)  获取指定网络UID接收的字节数
           

下面写一个小demo

MainActivity.java

package com.xxx.cn.trafficstatstest;

import android.app.Activity;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.net.TrafficStats;
import android.os.Bundle;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;


public class MainActivity extends Activity {
    private List apps = new ArrayList <ApplicationBean>();
    private ListView mListView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mListView = (ListView) findViewById(R.id.lv_app);
        getAppTrafficStatList();
        MyAdapter adapter = new MyAdapter(apps, this);
        mListView.setAdapter(adapter);
    }

    public void getAppTrafficStatList() {
        PackageManager pm = getPackageManager();
        //得到安装的所以应用
        List<PackageInfo> pinfos = pm.getInstalledPackages(PackageManager.GET_UNINSTALLED_PACKAGES |
                        PackageManager.GET_PERMISSIONS);
        //找出需要网络权限的应用,得到这个应用上传和下载的数据量
        for (PackageInfo info : pinfos) {
            String[] pers = info.requestedPermissions;

            if (pers != null && pers.length > ) {
                for (String per : pers)
                    //找到需要网络权限的应用
                    if ("android.permission.INTERNET".equals(per)) {
                        int uid = info.applicationInfo.uid;
                        String lable = (String) info.applicationInfo.loadLabel(pm);

                        Drawable icon = null;
                        try {
                            icon = pm.getApplicationIcon(info.packageName);
                        } catch (PackageManager.NameNotFoundException e) {
                            e.printStackTrace();
                        }

                        long rx = TrafficStats.getUidRxBytes(uid);
                        long tx = TrafficStats.getUidTxBytes(uid);

                        ApplicationBean app = new ApplicationBean();
                        app.setName(lable);
                        app.setIcon(icon);
                        app.setRx(rx);
                        app.setTx(tx);
                        apps.add(app);
                    }
            }
        }
    }

}
           

MyAdapter.java

package com.xxx.cn.trafficstatstest;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

public class MyAdapter extends BaseAdapter {
    private List mApps;
    private LayoutInflater inflater;

    public MyAdapter(List apps, Context context) {
        this.mApps = apps;
        this.inflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        return mApps.size();
    }

    @Override
    public Object getItem(int position) {
        return mApps.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder view;
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.app_item, null);
            view = new ViewHolder();
            view.name = (TextView) convertView.findViewById(R.id.app_name);
            view.icon = (ImageView) convertView.findViewById(R.id.app_icon);
            view.rx = (TextView) convertView.findViewById(R.id.app_rx);
            view.tx = (TextView) convertView.findViewById(R.id.app_tx);
            convertView.setTag(view);
        } else {
            view = (ViewHolder) convertView.getTag();
        }

        ApplicationBean app = (ApplicationBean) mApps.get(position);
        view.name.setText(app.getName());
        view.icon.setImageDrawable(app.getIcon());
        view.rx.setText("接收:" + app.getRx());
        view.tx.setText("上传:" + app.getTx());

        return convertView;
    }


    public static class ViewHolder {
        public TextView name;
        public ImageView icon;
        public TextView rx;
        public TextView tx;
    }
}
           

ApplicationBean.java

package com.xxx.cn.trafficstatstest;

import android.graphics.drawable.Drawable;

public class ApplicationBean {
    private String name;
    private Drawable icon;
    private long rx;
    private long tx;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Drawable getIcon() {
        return icon;
    }

    public void setIcon(Drawable icon) {
        this.icon = icon;
    }

    public long getTx() {
        return tx;
    }

    public void setTx(long tx) {
        this.tx = tx;
    }

    public long getRx() {
        return rx;
    }

    public void setRx(long rx) {
        this.rx = rx;
    }
}
           

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ListView
        android:id="@+id/lv_app"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>
           

app_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:padding="10dp"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/app_icon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:id="@+id/app_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <TextView
            android:id="@+id/app_tx"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <TextView
            android:id="@+id/app_rx"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

    </LinearLayout>

</LinearLayout>
           

运行界面如下:

Android中TrafficStats流量监控类

继续阅读