我在检查互联网速度时遇到问题。实际上我正在开发一个安卓应用程序,它可以在你的手机上测试你的网速。当我从 ISP 获得时,我制作了一个样本来测试速度及其显示写入速度,例如 7.3 Mbps。但在这个测试中,我使用下面的代码。
long startCon = System.currentTimeMillis(); Log.i("mymobilespeedtest", "start conn = " + startCon);
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(imageURL);
HttpResponse response = null;
try {
response = httpClient.execute(httpGet);
Log.i("SketchEffect","Executing http connection to download selected image.");
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
Log.i("FBAlbum", e.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
Log.i("FBAlbum", e.toString());
}
long endCon = System.currentTimeMillis();
Log.i("mymobilespeedtest", "endCon = " + endCon);
现在我想通过使用处理程序并使用不同的方法下载文件来显示互联网速度的进展。
在这种方法中,我使用下面的代码
String downloadFileUrl = "http://www.gregbugaj.com/wp-content/uploads/2009/03/dummy.txt";
URL url1 = new URL(downloadFileUrl);
URLConnection con1 = url1.openConnection();
con1.setUseCaches(false); stream1 = con1.getInputStream();
Message msgUpdateConnection = Message.obtain(mHandler,
MSG_UPDATE_CONNECTION_TIME);
msgUpdateConnection.arg1 = (int) connectionLatency;
mHandler.sendMessage(msgUpdateConnection);
long start = System.currentTimeMillis();
int currentByte = 0;
long updateStart = System.currentTimeMillis();
long updateDelta = 0;
int bytesInThreshold = 0;
int bytesIn = 0;
while (true) {
if ((currentByte = stream1.read()) == -1) {
break;
} else {
bytesIn++;
bytesInThreshold++;
baf.append((byte) currentByte);
if (updateDelta >= UPDATE_THRESHOLD) {
int progress = (int) ((bytesIn / (double) EXPECTED_SIZE_IN_BYTES) * 100);
Message msg = Message.obtain(mHandler,
MSG_UPDATE_STATUS,
calculate(updateDelta, bytesInThreshold));
msg.arg1 = progress;
msg.arg2 = bytesIn;
mHandler.sendMessage(msg);
// Reset
updateStart = System.currentTimeMillis();
bytesInThreshold = 0;
}
updateDelta = System.currentTimeMillis() - updateStart;
}
} if (downloadTime == 0) {
downloadTime = 1;
}
Message msg = Message.obtain(mHandler, MSG_COMPLETE_STATUS,
calculate(downloadTime, bytesIn));
msg.arg1 = bytesIn;
mHandler.sendMessage(msg);
通过上面的代码,我只能获得 0.8 或 1.o Mbps 的速度(以每秒兆位而不是字节为单位)