要確定android應用程序中的網速,首先需要從onlineserver下載一些文件。 爲什麼我們需要下載文件?檢查互聯網下載速度的平均值。
的,你需要像這樣的代碼
private class InternetSpeedTest
extends AsyncTask<String, Void, String> {
long startTime;
long endTime;
private long takenTime;
@Override
protected String doInBackground(String... paramVarArgs) {
startTime = System.currentTimeMillis();
Log.d(TAG, "doInBackground: StartTime" + startTime);
Bitmap bmp = null;
try {
URL ulrn = new URL(paramVarArgs[0]);
HttpURLConnection con = (HttpURLConnection) ulrn.openConnection();
InputStream is = con.getInputStream();
bmp = BitmapFactory.decodeStream(is);
Bitmap bitmap = bmp;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 99, stream);
byte[] imageInByte = stream.toByteArray();
long lengthbmp = imageInByte.length;
if (null != bmp) {
endTime = System.currentTimeMillis();
Log.d(TAG, "doInBackground: EndTIme" + endTime);
return lengthbmp + "";
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result) {
if (result != null) {
long dataSize = Integer.parseInt(result)/1024;
takenTime = endTime - startTime;
double s = (double) takenTime/1000;
double speed = dataSize/s;
Log.d(TAG, "onPostExecute: " + "" + new DecimalFormat("##.##").format(speed) + "kb/second");
}
}
在這段代碼將從Here
在doInBackground您將計算圖像的尺寸下載圖片後點擊這裏下載完成
Bitmap bitmap = bmp;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 99, stream);
byte[] imageInByte = stream.toByteArray();
long lengthbmp = imageInByte.length
最後一件事就是通過減去結束時間的形式開始時間來計算takenTime並且速度是(size/takenTime)
我希望它適合你
它適用於我 謝謝 –
其我所尋找的 非常感謝 –