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;
}