2013-08-07 46 views
1

我使用下面的代碼在Android中獲得流量數據使用 「TrafficStats」 類如何使用TrafficStats

public class TrafficStatisticsDemoActivity extends Activity { 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    TextView infoView = (TextView)findViewById(R.id.traffic_info); 
    String info = ""; 

    info += "Mobile Interface:\n"; 
    info += ("\tReceived: " + TrafficStats.getMobileRxBytes() + " bytes/" + TrafficStats.getMobileRxPackets() + " packets\n"); 
    info += ("\tTransmitted: " + TrafficStats.getMobileTxBytes() + " bytes/" + TrafficStats.getMobileTxPackets() + " packets\n"); 

    info += "All Network Interface:\n"; 
    info += ("\tReceived: " + TrafficStats.getTotalRxBytes() + " bytes/" + TrafficStats.getTotalRxPackets() + " packets\n"); 
    info += ("\tTransmitted: " + TrafficStats.getTotalTxBytes() + " bytes/" + TrafficStats.getTotalTxPackets() + " packets\n"); 

    infoView.setText(info); 
} 

main.xml中

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:orientation="vertical" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent"> 

<TextView 
android:layout_width="fill_parent" 
android:layout_height="wrap_content" 
android:id="@+id/traffic_info" 
android:padding="10dip"/> 

獲得在Android的WiFi數據計數器

它返回的值是Mobile(我相信是所有網絡的組合)。有沒有辦法獲得獨立的Wi-Fi和3G價值?另外我注意到有很多區分準確性問題。

回答

1
 TextView totData = (TextView)findViewById(R.id.totData); 

     TextView wifiTot = (TextView)findViewById(R.id.wifitotData); 
     TextView wifiTX = (TextView)findViewById(R.id.wifiUpData); 
     TextView wifiRX = (TextView)findViewById(R.id.wifiDownData); 

     TextView mobileTot = (TextView)findViewById(R.id.mobtotData); 
     TextView mobTX = (TextView)findViewById(R.id.mobUpData); 
     TextView mobRX = (TextView)findViewById(R.id.mobDownData); 

     /* 
     * Converting bytes to MB 
     */ 
     long rxBytes = TrafficStats.getTotalRxBytes()/1048576; 
     long txBytes = TrafficStats.getTotalTxBytes()/1048576; 

     long mobUpload = TrafficStats.getMobileTxBytes()/1048576; 
     long mobDown = TrafficStats.getMobileRxBytes()/1048576; 

     long wifiUpload = txBytes-(mobUpload); 
     long wifiDown = rxBytes-(mobDown); 

     wifiRX.setText(Long.toString(wifiDown)); 
     wifiTX.setText(Long.toString(wifiUpload)); 
     long wifitot = wifiUpload+wifiDown; 
     wifiTot.setText(Long.toString(wifitot)); 

     mobTX.setText(Long.toString(mobUpload)); 
     mobRX.setText(Long.toString(mobDown)); 
     long mobTot = mobUpload+mobDown; 
     mobileTot.setText(Long.toString(mobTot)); 

     totData.setText(Long.toString(wifitot+mobTot)); 
+1

如果您爲了更好地解釋發生了什麼,將會很好。 – Math

相關問題