如何衡量上传/下载速度和延迟在Android的WiFi连接下载速度、上传、WiFi、Android

2023-09-12 03:21:35 作者:华佗也治不好俄的蛋疼

我需要一些API或操纵code。通过它我可以衡量的上传/下载速度,从Android应用程序WiFi连接的延迟。

I need some api or manipulative code by which i can measure the upload/download speed and the latency in wifi connection from an android application.

推荐答案

您使用2.2(升级Froyo)或更高?

Are you using 2.2 (Froyo) or higher?

如果是这样,在你的应用程序中,进口流量统计,当你的应用程序正在使用互联网中添加以下内容。

If so, in your application, import Traffic Stats and when your application is using the internet add in the following.

下载/上传:

long BeforeTime = System.currentTimeMillis();
long TotalTxBeforeTest = TrafficStats.getTotalTxBytes();
long TotalRxBeforeTest = TrafficStats.getTotalRxBytes();

/* DO WHATEVER NETWORK STUFF YOU NEED TO DO */

long TotalTxAfterTest = TrafficStats.getTotalTxBytes();
long TotalRxAfterTest = TrafficStats.getTotalRxBytes();
long AfterTime = System.currentTimeMillis();

double TimeDifference = AfterTime - BeforeTime;

double rxDiff = TotalRxAfterTest - TotalRxBeforeTest;
double txDiff = TotalTxAfterTest - TotalTxBeforeTest;

if((rxDiff != 0) && (txDiff != 0)) {
    double rxBPS = (rxDiff / (TimeDifference/1000)); // total rx bytes per second.
    double txBPS = (txDiff / (TimeDifference/1000)); // total tx bytes per second.
    testing[0] = String.valueOf(rxBPS) + "B/s. Total rx = " + rxDiff;
    testing[1] = String.valueOf(txBPS) + "B/s. Total tx = " + txDiff;
}
else {
    testing[0] = "No uploaded or downloaded bytes.";
}

现在你有测试[0] 是你的下载速度(大约)和测试[1] 是上传速度(大约)

Now you have testing[0] is your download speed (roughly) and testing[1] is your upload speed (roughly)

只要确保你只调用此code时,你实际上是在做网络通信或时间会扭曲你的结果。

Just make sure you are only calling this code when you are actually doing network communication or the time will skew your results.

根据潜伏期,没有什么是伟大的在那里。我写这是未经测试,但应该工作正常,但也有可能更好的解决方案。

As per latency, there is nothing that great out there. I've written this which is untested, but should work ok, but there are likely better solutions available.

延迟

String host = YOUR_HOST
HttpGet request = new HttpGet(host);
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 3000);
HttpClient httpClient = new DefaultHttpClient(httpParameters);

for(int i=0; i<5; i++) {
    long BeforeTime = System.currentTimeMillis();
    HttpResponse response = httpClient.execute(request);
    long AfterTime = System.currentTimeMillis();
    Long TimeDifference = AfterTime - BeforeTime;
    time[i] = TimeDifference 
}

注:请记住,这个就不说了等待时间在你的使用时间,但给你经验丰富,你是在一个特定的时间段使用网络上的等待时间的想法。此外,这是不是达到网络时间说平通常会做请求的请求和响应时间。

Note: Keep in mind that this will not say the latency at your time of use, but give you an idea of the latency experienced on the network you are using at a particular period of time. Also, this is the request and response time, instead of the request reaching the network time as say "ping" would normally do.