2012年10月29日 星期一

Writing Network Monitor - 1

Simple Network Monitor that display network information on screen.
Capture data in a file.





package com.hong.network.monitor;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.TimeZone;
import android.net.TrafficStats;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
/* Network Monitor
 * 26-10-2012 Initial Create
 *
 * Know issue:
 * - WiFi Turn off will reset the counter
 * - No Function for monitor WiFi only => WiFi = Total - Mobile may include other information
 *
 * 
 */
public class MainActivity extends Activity {
 private Handler mHandler = new Handler();
 private long mStartRX = 0;
 private long mStartTX = 0;

 private long systemMs;

 private long mStartMobileRX = 0;
 private long mStartMobileTX = 0;

 private TextView RX,TX;
 private Button Start;

 private boolean start=false;
 File fOut = null;
 OutputStreamWriter osw = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        Log.i("Network Mon","onCreate " + start);
       
        mStartRX = TrafficStats.getTotalRxBytes();
        mStartTX = TrafficStats.getTotalTxBytes();
        mStartMobileRX = TrafficStats.getMobileRxBytes();
        mStartMobileTX = TrafficStats.getMobileTxBytes();
  RX = (TextView)findViewById(R.id.RX);
  TX = (TextView)findViewById(R.id.TX);
  Start = (Button)findViewById(R.id.start);
     Start.setOnClickListener(capture);
    
        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);
        }      
    }
   
    @Override
    public void onPause() {
        super.onPause();
        Log.i("Network Mon","onPause " + start);
    }
   
    @Override
    public void onResume() {
        super.onResume();
        Log.i("Network Mon","onResume " + start);
    }
   
    @Override
    public void onStop() {
        super.onStop();
        Log.i("Network Mon","onStop " + start);
    }
   
    @Override
    public void onStart() {
        super.onStart();
        Log.i("Network Mon","onStart" + start);
    }
   
   
    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i("Network Mon","onDestory " + start);
       
        mHandler.removeCallbacks(mRunnable);
  start = false;
  Start.setText("start");
  if(osw != null) {
   try {
    osw.close();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   osw = null;
  }
    }
   
    public OnClickListener capture = new OnClickListener(){
        public void onClick(View v) {
         if(start) {
          if(osw != null) {
     try {
      osw.close();
     } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
     osw=null;
          }
          Start.setText("start");
          start = false;
         }
         else {
          try{
           systemMs = System.currentTimeMillis();
           Calendar localCalendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        fOut = new File(Environment.getExternalStorageDirectory() + "/" + sdf.format(localCalendar.getTime()) + ".txt");
           osw = new FileWriter(fOut);
           osw.write("Time(s), Rx Mobile (Bytes), Rx Total (Bytes), Tx Mobile (Bytes), Tx Total (Bytes)");
          } catch (Exception e) {
           Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
          }
          Start.setText("stop");
          start = true;
         
         }
        }
     };
   
    private final Runnable mRunnable = new Runnable() {
     public void run() {
      long rxBytes = TrafficStats.getTotalRxBytes();
      long rxMobilesBytes = TrafficStats.getMobileRxBytes();
     
      long txBytes = TrafficStats.getTotalTxBytes();
      long txMobilesBytes = TrafficStats.getMobileTxBytes();
     
      // Mobile, Total
      Log.i("Network Stats","Traffic RX:" + Long.toString(mStartMobileRX) + ", " + Long.toString(rxMobilesBytes) + ", " + Long.toString(mStartRX) + ", " + Long.toString(rxBytes));    
      Log.i("Network Stats","Traffic TX:" + Long.toString(mStartMobileTX) + ", " + Long.toString(txMobilesBytes) + ", " + Long.toString(mStartTX) + ", " + Long.toString(txBytes));    
     
      RX.setText("" + Long.toString(rxMobilesBytes - mStartMobileRX) + ", " + Long.toString(rxBytes - mStartRX));
      TX.setText("" + Long.toString(txMobilesBytes - mStartMobileTX) + ", " + Long.toString(txBytes -mStartTX));
      if(start) {
       try {
     osw.write(String.format("%06d ", (System.currentTimeMillis() - systemMs)/1000) + RX.getText() + ", " + TX.getText() + "\n");
     Log.i("Network Saved",RX.getText() + ", " + TX.getText());
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
      }
      if(rxBytes - mStartRX < 0) {
       mStartRX = 0;
       Log.i("Network Stats", "Traffic Rx WiFi Reset");
      }
      else {
       mStartRX = rxBytes;      
      }
            
      if(txBytes - mStartTX < 0) {
       mStartTX = 0;
       Log.i("Network Stats", "Traffic Tx WiFi Reset");
      }
      else {
       mStartTX = txBytes;      
      }    
      mStartMobileRX = rxMobilesBytes;
      mStartMobileTX = txMobilesBytes;
     
      mHandler.postDelayed(mRunnable, 1000);
     }
    };
   
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}

Writing Network Monitor

Objective:
Writing Network Monitor to capture Mobile and WiFi

Implementation:
1. Can't Rotate
2. Three Tab - Mobile, WiFi and Total
3. For each Tab - Graph for 1 minite and a table display all information (Up, Down, all, Day, Week and Month)
4. Save all the data in SQLite.
5. Check for data usage for a period.

Network Monitor

class TrafficStats

        TrafficStats.getTotalRxBytes();
        TrafficStats.getTotalTxBytes();
        TrafficStats.getMobileRxBytes();
        TrafficStats.getMobileTxBytes();

problem
 - WiFi Turn off will reset the counter
 - No Function for monitor WiFi only => WiFi = Total - Mobile may include other information