2013-06-18 77 views
-1

如何統計Android設備上的網絡數據包數量?Android:如何統計網絡數據包?

我需要使它所以我的應用程序在以往500包就將此一+1(輸入/輸出)

我使用Eclipse。

+1

也許你應該解析netstat命令行程序的結果和comprare更改? –

回答

0

在閱讀Michal評論之後,我資助了TrafficStats類。

https://developer.android.com/reference/android/net/TrafficStats.html

new TrafficStats().getTotalTxPackets(); 

下面是我的應用程序看起來怎麼樣了。

public class MainActivity extends Activity { 
    private TrafficStats ts; 
    private long totalTNumberOfPackets; 
    private TextView tv_numberOfPackets; 
    private NotificationManager mgr; 
    private WebView wv; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     if(!(totalTNumberOfPackets == TrafficStats.UNSUPPORTED)) 
     { 
      mgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 
      wv = (WebView) findViewById(R.id.wv); 
      wv.loadUrl("file:///android_asset/info.html"); 
      intiNotification(); 

      new Thread(
        new Runnable() { 
         public void run() { 
          while(true) 
          { 
           intiNotification(); 
           try { 
            Thread.sleep(1000); 
           } catch (InterruptedException e) { 
            // TODO Auto-generated catch block 
            e.printStackTrace(); 
           } 
          } 
         } 
        } 
       // Starts the thread by calling the run() method in its Runnable 
       ).start(); 
     } 
     else 
     { 
      Toast.makeText(this, "Hov.. din Android understøtter ikke denne app!!", Toast.LENGTH_LONG).show(); 
     } 
    } 
    public static long round(Long unrounded, int precision, int roundingMode) 
    { 
     BigDecimal bd = new BigDecimal(unrounded); 
     BigDecimal rounded = bd.setScale(precision, roundingMode); 
     return rounded.longValue(); 
    } 
    public Long usersTotalNumberOfLogginger() 
    { 
     return round(new TrafficStats().getTotalTxPackets()/500, 0, BigDecimal.ROUND_HALF_DOWN); 
    } 
    @SuppressWarnings("deprecation") 
    private void intiNotification() { 
      Notification note = new Notification(R.drawable.ic_launcher, 
        "Logningstæller ("+usersTotalNumberOfLogginger()+" gange)", System.currentTimeMillis()); 
      PendingIntent i = PendingIntent.getActivity(this, 0, new Intent(
        this, MainActivity.class), Notification.FLAG_ONGOING_EVENT); 
      note.setLatestEventInfo(this, "Logningstæller", "Du er blivet logget "+String.valueOf(usersTotalNumberOfLogginger())+" gange", 
        i); 
      // note.number = ++count; 
      note.flags |= Notification.FLAG_ONGOING_EVENT; 
      mgr.notify(0, note); 
    } 
    @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; 
    } 
}