效果图:
需要注意的是,本代码只有部署在真机上时才会有效果,当不熟在模拟器时很可能不会有效果
代码实现:
1、traffic_manager_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="@+id/iv_appicon"
android:layout_width="35dip"
android:layout_height="35dip"
android:scaleType="fitXY"
android:src="@drawable/ic_launcher" />
<TextView
android:id="@+id/tv_appname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/iv_appicon"
android:text="我最摇摆"
android:textColor="@android:color/white"
android:textSize="20sp" />
<TextView
android:id="@+id/tv_apptarffic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:text="20MB"
android:textColor="@android:color/white"
android:textSize="20sp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/tv_appname"
android:layout_toRightOf="@id/iv_appicon"
android:orientation="horizontal" >
<TextView
android:id="@+id/tv_apptx"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="80dp"
android:text="上传:20MB"
android:textSize="14sp" />
<TextView
android:id="@+id/tv_apprx"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="下载:20MB"
android:textSize="14sp" />
</LinearLayout>
</RelativeLayout>
2、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:background="@android:color/background_dark"
android:orientation="vertical" >
<TableLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TableRow
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="2g/3g" />
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="wifi" />
</TableRow>
<TableRow
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/tv_traffic_manager_mobile"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="200Mb" />
<TextView
android:id="@+id/tv_traffic_manager_wifi"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="50MB" />
</TableRow>
</TableLayout>
<SlidingDrawer
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:content="@+id/lv_traffic_manager_content"
android:handle="@+id/handle"
android:orientation="vertical" >
<ImageView
android:id="@id/handle"
android:layout_width="30dp"
android:layout_height="30dp"
android:src="@drawable/notification" />
<ListView
android:id="@id/lv_traffic_manager_content"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</ListView>
</SlidingDrawer>
</LinearLayout>
3、TrafficManagerActivity
package com.njupt.testtracfficstate;
import java.util.ArrayList;
import java.util.List;
import android.net.TrafficStats;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity {
protected static final int SUCCESS_GET_TRAFFICINFO = 0;
/** Called when the activity is first created. */
private TextView tv_traffic_manager_mobile;
private TextView tv_traffic_manager_wifi;
private ListView lv_traffic_manager_content;
private TrafficManagerService trafficManagerService;
private List<TrafficInfo> trafficInfos;
private List<TrafficInfo> realTrafficInfos;
private TrafficManagerAdapter mAdapter;
private Handler mHandler = new Handler(){
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case SUCCESS_GET_TRAFFICINFO:
mAdapter = new TrafficManagerAdapter(getApplicationContext());
lv_traffic_manager_content.setAdapter(mAdapter);
break;
default:
break;
}
};
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/* 2g3g 接收流量
TrafficStats.getMobileRxBytes();
//2g/3g 接收的包
TrafficStats.getMobileRxPackets();
//2g/3g 上传的流量
TrafficStats.getMobileTxBytes();
//2g/3g 上传的包
TrafficStats.getMobileTxPackets();
// 手机总共接收的流量
TrafficStats.getTotalRxBytes();
// 手机总共上传的流量
TrafficStats.getTotalTxBytes();
//得到么个应用程序接收的流量
TrafficStats.getUidRxBytes(uid);
TrafficStats.getUidTxBytes(uid);*/
tv_traffic_manager_mobile = (TextView) findViewById(R.id.tv_traffic_manager_mobile);
tv_traffic_manager_wifi = (TextView) findViewById(R.id.tv_traffic_manager_wifi);
lv_traffic_manager_content = (ListView) findViewById(R.id.lv_traffic_manager_content);
tv_traffic_manager_mobile.setText(TextFormat.formatByte(getMobileTotal()));
tv_traffic_manager_wifi.setText(TextFormat.formatByte(getWifiTotal()));
trafficManagerService = new TrafficManagerService(this);
new Thread(){
public void run() {
trafficInfos = trafficManagerService.getLauncherTrafficInfos();
realTrafficInfos = new ArrayList<TrafficInfo>();
for(TrafficInfo info:trafficInfos){
if(TrafficStats.getUidRxBytes(info.getUid()) == -1 && TrafficStats.getUidTxBytes(info.getUid()) == -1){
//
}else{
realTrafficInfos.add(info);
}
}
Message msg = new Message();
msg.what = SUCCESS_GET_TRAFFICINFO;
mHandler.sendMessage(msg);
};
}.start();
}
/**
* 2g/3g的总流量
* @return
*/
private long getMobileTotal(){
long mobile_rx = TrafficStats.getMobileRxBytes();
long mobile_tx = TrafficStats.getMobileTxBytes();
return mobile_rx + mobile_tx;
}
/**
* 得到手机的总流量
* @return
*/
private long getTotal(){
return TrafficStats.getTotalRxBytes() + TrafficStats.getTotalTxBytes();
}
/**
* 得到wifi的总流量
* @return
*/
private long getWifiTotal(){
return getTotal() - getMobileTotal();
}
static class ViewHolder{
ImageView iv_appicon;
TextView tv_appname;
TextView tv_apptraffic;
TextView tv_apptx;
TextView tv_apprx;
}
private final class TrafficManagerAdapter extends BaseAdapter{
private LayoutInflater mInflater;
public TrafficManagerAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return realTrafficInfos.size();
}
public Object getItem(int position) {
return realTrafficInfos.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
ViewHolder holder = null;
if(convertView != null){
view = convertView;
holder = (ViewHolder) view.getTag();
}else{
view = mInflater.inflate(R.layout.traffic_manager_item, null);
holder = new ViewHolder();
holder.iv_appicon = (ImageView) view.findViewById(R.id.iv_appicon);
holder.tv_appname = (TextView) view.findViewById(R.id.tv_appname);
holder.tv_apptraffic = (TextView) view.findViewById(R.id.tv_apptarffic);
holder.tv_apptx = (TextView) view.findViewById(R.id.tv_apptx);
holder.tv_apprx = (TextView) view.findViewById(R.id.tv_apprx);
view.setTag(holder);
}
TrafficInfo trafficInfo = realTrafficInfos.get(position);
holder.iv_appicon.setImageDrawable(trafficInfo.getAppicon());
holder.tv_appname.setText(trafficInfo.getAppname());
int uid = trafficInfo.getUid();
long tx = TrafficStats.getUidTxBytes(uid);
if(tx == -1){
tx = 0;
}
long rx = TrafficStats.getUidRxBytes(uid);
if(rx == -1){
rx = 0;
}
long total = tx + rx;
holder.tv_apptraffic.setText(TextFormat.formatByte(total));
holder.tv_apptx.setText("上传:" + TextFormat.formatByte(tx));
holder.tv_apprx.setText("下载:" + TextFormat.formatByte(rx));
return view;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
4、TrafficManagerService
package com.njupt.testtracfficstate;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
public class TrafficManagerService {
private Context context;
private PackageManager pm;
public TrafficManagerService(Context context) {
this.context = context;
pm = context.getPackageManager();
}
/**
* 得到所有能启动的应用
* @return
*/
public List<TrafficInfo> getLauncherTrafficInfos(){
List<TrafficInfo> trafficInfos = new ArrayList<TrafficInfo>();
//查询能够启动的应用程序
Intent intent = new Intent();
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
//ResolveInfo 就类似于一个IntentFilter
List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
for(ResolveInfo info:resolveInfos){
ApplicationInfo appInfo = info.activityInfo.applicationInfo;
Drawable appicon = appInfo.loadIcon(pm);
String appname = appInfo.loadLabel(pm).toString();
String packageName = appInfo.packageName;
int uid = appInfo.uid;
trafficInfos.add(new TrafficInfo(appicon, appname, packageName, uid));
}
return trafficInfos;
}
}
5、TrafficInfo
package com.njupt.testtracfficstate;
import android.graphics.drawable.Drawable;
public class TrafficInfo {
private Drawable appicon;
private String appname;
private String packageName;
private int uid;
public TrafficInfo() {
super();
}
public TrafficInfo(Drawable appicon, String appname, String packageName,
int uid) {
super();
this.appicon = appicon;
this.appname = appname;
this.packageName = packageName;
this.uid = uid;
}
public Drawable getAppicon() {
return appicon;
}
public void setAppicon(Drawable appicon) {
this.appicon = appicon;
}
public String getAppname() {
return appname;
}
public void setAppname(String appname) {
this.appname = appname;
}
public String getPackageName() {
return packageName;
}
public void setPackageName(String packageName) {
this.packageName = packageName;
}
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
@Override
public String toString() {
return "TrafficInfo [appicon=" + appicon + ", appname=" + appname
+ ", packageName=" + packageName + ", uid=" + uid + "]";
}
}
6、TextFormat
package com.njupt.testtracfficstate;
import java.text.DecimalFormat;
public class TextFormat {
// 23.87MB 00.87MB/KB byte
public static String formatByte(long data) {
DecimalFormat format = new DecimalFormat("##.##");
if (data < 1024) {
return data + "bytes";
} else if (data < 1024 * 1024) {
return format.format(data / 1024f) + "KB";
} else if (data < 1024 * 1024 * 1024) {
return format.format(data / 1024f / 1024f) + "MB";
} else if (data < 1024 * 1024 * 1024 * 1024) {
return format.format(data / 1024f / 1024f / 1024f) + "GB";
} else {
return "超出统计返回";
}
}
}