我在檢查網速時遇到了一個問題。其實我正在開發一個Android應用程序,它可以測試你的手機上網速度。我製作了一個樣本來測試速度及其顯示寫入速度,例如從我的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的速度(以兆比特每secons不是字節)
如果你想測量下載速度,你應該擺脫消息處理代碼。從套接字讀取,不要將讀取的字節存儲在任何地方。現在,由於代碼中的瓶頸,速度可能會降低。 –