Android流量统计

去除本地WIFI流量,只统计2G/3G流量
数据存储:
package com.android.oa.PublicTool;
//获取网络数据
public class HttpData {
 public static String userId = "";
 public static String checkCode = "";
 public static boolean isNetwork = false;
 public static String GetData(Context context, String httpUrl) {
  getTotalBytes(context);
  try
  {
   URL urlString = new URL(httpUrl);
   HttpURLConnection httpconn = (HttpURLConnection) urlString.openConnection();
   // httpconn.setRequestProperty("Cookie", cookie);
   httpconn.setRequestProperty("userId", userId);
   httpconn.setRequestProperty("checkCode", checkCode);
   InputStreamReader inputReader = new InputStreamReader(httpconn.getInputStream());
   BufferedReader bufReader = new BufferedReader(inputReader);
   String line = "";
   String Data = "";
   while ((line = bufReader.readLine()) != null) {
    Data += line;
   }
   getRunningAppProcessInfo(context);
   return Data;
  } catch (IOException i)
  {
   return null;
  }
 }
 public static String PostData(Context context, String postUrl, String postData)
 {
  getTotalBytes(context);
  try
  {
   URL url = new URL(postUrl);
   HttpURLConnection conn = (HttpURLConnection) url.openConnection();
   conn.setRequestMethod("POST");
   conn.setDoInput(true);
   conn.setDoOutput(true);
   // conn.setRequestProperty("accept",
   // "text/html, application/xml;q=0.9, application/xhtml+xml, image/png, image/jpeg, image/gif, image/x-xbitmap");
   // conn.setRequestProperty("User-Agent",
   // "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
   // conn.setRequestProperty("Cookie",cookie);
   conn.setInstanceFollowRedirects(true);
   conn.setUseCaches(true);
   conn.setRequestProperty("userId", userId);
   conn.setRequestProperty("checkCode", checkCode);
   OutputStream os = conn.getOutputStream();
   os.write(postData.getBytes("utf-8"));
   os.close();
   BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
   String line;
   String result = "";
   while ((line = br.readLine()) != null) {
    result += line;
   }
   br.close();
   getRunningAppProcessInfo(context);
   return result;
  } catch (Exception ee)
  {
   return null;
  }
 }
 
 private static long TR = 0, WF = 0, TO = 0,TM1=0,TM2=0;
 public static void getTotalBytes(Context context) {//获取总流量
  isNull(context);
  if (TrafficStats.getMobileRxBytes() == -1)
  {
   isNetwork = false;
  } else {
   isNetwork = true;
  }
  TO = TrafficStats.getUidRxBytes(getUid(context))+ TrafficStats.getUidTxBytes(getUid(context));
  WF = TO;
  TR = TO;
 }
 public static void getCurrentBytes(final Context context)//获取当前流量值
 {
  ((Activity) context).runOnUiThread(new Runnable() {
   @Override
   public void run() {
    // To change body of implemented methods use File | Settings |
    // File Templates.
    String date = DateTimeHelper.getDate();
    // String time=DateTimeHelper.getDateTime();
    DatabaseHelper dbHelper = new DatabaseHelper(context);
    TR = TR - TO;
    WF = WF - TO;
    if (dbHelper.Exists(("select 1 from NetworkBytes where Time='" + date + "'")))//修改流量记录值
    {
     Cursor cursor = dbHelper.Select("select TRBytes,WifiBytes from NetworkBytes where Time='" + date + "'");
     for (cursor.moveToFirst(); !(cursor.isAfterLast()); cursor.moveToNext()) {
      long tem1=0,tem2=0;
      tem1=Long.parseLong(cursor.getString(cursor.getColumnIndex("TRBytes")));
      tem2=Long.parseLong(cursor.getString(cursor.getColumnIndex("WifiBytes")));
      TM1=TR+tem1;
            TM2=WF+tem2;
      break;
     }
     dbHelper.Update(String.format("update NetworkBytes set TRBytes=TRBytes+%s,WifiBytes=WifiBytes+%s where Time='" + date + "'", String.valueOf(TR),String.valueOf(WF)));
    }
    else
    {
     dbHelper.AddString(String.format("insert into NetworkBytes(TRBytes,WifiBytes,Time) values(%s,%s,'%s')",String.valueOf(TR), String.valueOf(WF), date));
    }
    dbHelper.close();
   }
  });
 }
 private static void getRunningAppProcessInfo(final Context context)//获取指定应用消耗流量值 
 {
  if (isNetwork) {
   int uid = getUid(context);
   if (isWifi(context)) {
    WF = TrafficStats.getUidRxBytes(uid) + TrafficStats.getUidTxBytes(uid);
   } else {
    TR = TrafficStats.getUidRxBytes(uid) + TrafficStats.getUidTxBytes(uid);
   }
  }
  getCurrentBytes(context);
 }
 private static int getUid(Context context) {
  int tem = 0;
  // 通过调用ActivityManager的getRunningAppProcesses()方法获得系统里所有正在运行的进程
  ActivityManager _ActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
  List<RunningAppProcessInfo> appProcessList = _ActivityManager.getRunningAppProcesses();
  for (ActivityManager.RunningAppProcessInfo appProcessInfo : appProcessList) {
   // 进程ID号
   // int pid = appProcessInfo.pid;
   // 用户ID 类似于Linux的权限不同,ID也就不同 比如 root等
   // int uid = appProcessInfo.uid;
   if (appProcessInfo.processName.equals("com.android.oa")) {
    tem = appProcessInfo.uid;
    break;
   }
  }
  return tem;
 }
 private static boolean isWifi(Context mContext)//判断流量类型是否为无线网络
 {
  ConnectivityManager connectivityManager = (ConnectivityManager) mContext
    .getSystemService(Context.CONNECTIVITY_SERVICE);
  NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
  if (activeNetInfo != null
    && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
   return true;
  }
  return false;
 }
}
流量使用记录显示:


package com.android.oa.Setting;
public class NetworkBytes extends BaseActivity {
 private ProgressDialog dialog;
 private static String dayBytes, monthBytes, allBytes;
 private ImageView dreset, mreset, areset;
 private TextView daytv, monthtv, alltv;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);
  setContentView(R.layout.liuliang);
  //dreset = (ImageView) findViewById(R.id.NBdreset);
  daytv = (TextView) findViewById(R.id.NBdbytes);
  monthtv = (TextView) findViewById(R.id.NBmbytes);
  // mreset=(ImageView)findViewById(R.id.NBmreset);
  alltv = (TextView) findViewById(R.id.NBabytes);
  dbHelper = new DatabaseHelper(NetworkBytes.this);
  dialog = DialogHelper.createDialog(NetworkBytes.this,
    DialogFinal.titleWait, DialogFinal.tileLoad);
  dialog.show();
  new Thread(new newThread()).start();
 }
 Handler myHandler = new Handler() {
  public void handleMessage(Message msg) {
   switch (msg.what) {
    case 1 :
     daytv.setText("本日已使用GPRS流量:" + dayBytes);
     monthtv.setText("本月已使用GPRS流量:" + monthBytes);
     alltv.setText("已使用GPRS总流量:" + allBytes);
     dialog.dismiss();
     break;
   }
   super.handleMessage(msg);
  }
 };
 class newThread implements Runnable {
  public void run() {
   Message message = new Message();
   message.what = 1;
   getBytesData();
   NetworkBytes.this.myHandler.sendMessage(message);
  }
 }
 private void getBytesData() {//查表获取数据
  dbHelper = new DatabaseHelper(NetworkBytes.this);
  //String sql = "select TRBytes,WifiBytes,Time from NetworkBytes where strftime('%m',Time)=strftime('%m','now')";
  String sql = "select TRBytes,Time from NetworkBytes";//where strftime('%m',Time)=strftime('%m','now')";
  Cursor cursor = dbHelper.Select(sql);
  long dtem = 0, mtem = 0, atem = 0;
  for (cursor.moveToFirst(); !(cursor.isAfterLast()); cursor.moveToNext()) {
   atem +=Long.parseLong(cursor.getString(cursor.getColumnIndex("TRBytes")));// 总流量
   int tem = CompareDate(cursor.getString(cursor.getColumnIndex("Time")));
   if (tem == 1) {
    dtem = Long.parseLong(cursor.getString(cursor.getColumnIndex("TRBytes")));// 日流量
    mtem += dtem;
   } else if (tem == 2) {
    mtem += Long.parseLong(cursor.getString(cursor.getColumnIndex("TRBytes")));// - Integer.parseInt(cursor.getString(cursor.getColumnIndex("WifiBytes")));// 月流量
   }
   // System.out.println("TRBytes-->"+cursor.getString(cursor.getColumnIndex("TRBytes"))+"WifiBytes-->"+cursor.getString(cursor.getColumnIndex("WifiBytes"))+"time-->"+cursor.getString(cursor.getColumnIndex("Time")));
  }
  dayBytes = unitExchange(dtem);
  monthBytes = unitExchange(mtem);
  allBytes = unitExchange(atem);
 }
 private static int CompareDate(String date) {// 比较是否为当日流量统计
  SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
  SimpleDateFormat monthmatter = new SimpleDateFormat("MM");
  Date setDate = null;
  int dm=0;
  try {
   setDate = formatter.parse(date);
  } catch (ParseException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  Date curDate = new Date(System.currentTimeMillis());
  String c = formatter.format(curDate);
  String s = formatter.format(setDate);
  String cm = monthmatter.format(curDate);
  String sm = monthmatter.format(setDate);
  if (c.equals(s)) {
   dm=1;
  }
  else if (cm.equals(sm))
  {
   dm= 2;
  }
  return dm;
 }
 private String unitExchange(long count) {// 单位换算
  double tem = count / (1024 * 1024.0);
  DecimalFormat df = new DecimalFormat("0");
  DecimalFormat dfs = new DecimalFormat("0.00");
  if (Integer.parseInt(df.format(tem)) > 0) {
   return dfs.format(tem) + " M";
  } else {
   return dfs.format(count / 1024.0) + " KB";
  }
 }
}

posted @ 2013-05-19 12:17  BicycleBoy  阅读(605)  评论(0编辑  收藏  举报