我正在尝试使用TrafficStats监控设备消耗的WiFi使用量,但是当我尝试这样做时,会产生非常大的值。即使在设备上执行恢复出厂设置后,我使用的数据量也非常大(重置设备一分钟内411970 MB的数据使用量似乎不准确)
非常感谢任何建议!
来源:
public class WifiMonitor extends Activity {
Button sendButton;
EditText msgTextField;
private PendingIntent pendingIntent;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView infoView = (TextView) findViewById(R.id.traffic_info);
String info = "";
info += ("\tWifi Data Usage: " + TrafficStats.getTotalRxBytes() + TrafficStats.getTotalTxBytes() / 1000000 + " MB");
infoView.setText(info);
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage("3055555555", null, info, null, null);
if (info.length() > 0) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://wifiusage.atwebpages.com/receiver.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("message", info));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
Intent myIntent = new Intent(WifiMonitor.this, Alarm.class);
pendingIntent = PendingIntent.getService(WifiMonitor.this, 0,
myIntent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 10);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), 30 * 1000, pendingIntent);
}
}
答案 0 :(得分:1)
您正在添加字节数
TrafficStats.getTotalRxBytes() + TrafficStats.getTotalTxBytes() / 1000000
所以你在一起写两个数字,中间没有空格或任何分隔符(第一个字节数,然后是MB数)。
使用括号来破坏操作
(TrafficStats.getTotalRxBytes() + TrafficStats.getTotalTxBytes()) / 1000000
答案 1 :(得分:1)
这些是字节! 为了得到正确的结果,你必须像这样划分字节: