AndroidTools Git地址:https://github.com/wisesun7/AndroidTools.git
本方法的思路是,從遠程服務器中實時下載一次測試文件,記錄開始時間與結束時間,通過下載到本地的文件大小即可計算出實際下載速度。需要注意的是:
- 一定要設置超時時間,防止網速過慢時,長時間處於下載過程,本方法中設置的爲20秒
- 測速完畢後刪除本地已下載文件,防止佔用存儲空間
- 測速要在子線程中進行,主線程可用動畫標註進程
- 本方法中使用的公司提供的服務器,因此地址無法公開,見諒~
/**
*
* @param NET_TEST_PATH 下載本地路徑
* @param NET_TEST_URL 遠程下載路徑
* @return
*/
public float checkNetSpeed(String NET_TEST_PATH , String NET_TEST_URL) {
float testSpeed = 0;
int fileLength = 0;
long startTime = 0;
long endTime = 0;
long middleTime = 0;
final String fileName = "test.apk";
HttpURLConnection conn = null;
InputStream is = null;
FileOutputStream fos = null;
File tmpFile = new File(NET_TEST_PATH);
if (!tmpFile.exists()) {
tmpFile.mkdir();
}
final File file = new File(NET_TEST_PATH + fileName);
try {
URL url = new URL(NET_TEST_URL);
try {
conn = (HttpURLConnection) url.openConnection();
fileLength = conn.getContentLength();
if (fileLength <= 0) {
Log.d(TAG, "fileLength <= 0");
return 0;
}
startTime = SystemClock.uptimeMillis() / 1000;
//startTime = System.currentTimeMillis() / 1000;
is = conn.getInputStream();
fos = new FileOutputStream(file);
byte[] buf = new byte[256];
conn.connect();
if (conn.getResponseCode() >= 400) {
Log.d(TAG, "conn.getResponseCode() = " + conn.getResponseCode());
return 0;
} else {
while (true) {
if (is != null) {
int numRead = is.read(buf);
if (numRead <= 0) {
break;
} else {
fos.write(buf, 0, numRead);
}
} else {
break;
}
middleTime = SystemClock.uptimeMillis()/1000;
//設置超時時間20s
if (middleTime - startTime >= 20){
break;
}
}
}
endTime = SystemClock.uptimeMillis()/1000;
//endTime = System.currentTimeMillis() / 1000;
Log.d(TAG, "endTime = " + endTime);
} catch (IOException e) {
Log.e(TAG,"error message : " + e.getMessage());
} finally {
if (conn != null) {
conn.disconnect();
}
try {
if (fos != null) {
fos.close();
}
if (is != null) {
is.close();
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
File readyFile = new File(NET_TEST_PATH + fileName);
long downLength = readyFile.length();
Log.d(TAG,"downLength : " + downLength / 1024 / 1024);
//刪除本地已下載文件,防止佔用存儲空間
FileUtils.deleteFile(NET_TEST_PATH + fileName);
Log.d(TAG, "fileLength" + (fileLength / (1024 * 1024)));
Log.d(TAG, "spend time" + (endTime - startTime));
if ( (endTime - startTime) > 0){
testSpeed = (downLength / (1024)) / (endTime - startTime);
}else {
testSpeed = 0;
}
return testSpeed;
}