在我的Android应用程序中,我使用WIFI链接速度来获得WIFI的速度 并在下载文件之前获取文件的长度内容 然后我试图在下载文件之前获得下载的时间 但是我得到的时间不正确,我不知道为什么!
这是我估算下载前的时间的代码
URL u = new URL(url);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.connect();
contentLength = Long.parseLong(c.getHeaderField("Content-Length"));
System.out.println("content"+contentLength);
float contentLength_float=contentLength/(float)(1000*1000);//migabyte
float speed=((float)(mActivity.speed_wifi()))/(float)8;//convert mbps(migabit) to migabyte ps
float sec=contentLength_float/speed;//get the sec from m/m/s
和功能wifi速度()
public int speed_wifi()
{
WifiManager mainWifi;
mainWifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = mainWifi.getConnectionInfo();
int speed=0;
if(wifiInfo.getBSSID()!=null)
{
speed=wifiInfo.getLinkSpeed();
}
return speed;
}
答案 0 :(得分:3)
使用该功能获得的wifi链接速度是手机中wifi可以达到的最高速度,它不是实际速度。 在下载开始之前无法确定wifi速度。 您可以做的是,根据当前下载速度开始显示下载开始时的估计时间。为此 -
因此,通过这种方式,您可以在下载开始后的1或2秒内开始显示估计的时间。
答案 1 :(得分:1)
使用AysnTask
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
// this will be useful to display download percentage
// might be -1: server did not report the length
int fileLength = connection.getContentLength();
// download the file
input = connection.getInputStream();
output = new FileOutputStream("/sdcard/file_name.extension");
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
// allow canceling with back button
if (isCancelled()) {
input.close();
return null;
}
total += count;
// publishing the progress....
if (fileLength > 0) // only if total length is known
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}