我试图让一个应用程序,可以帮助我评估,以从网络资源下载文件的时间。我发现2个样品:
I am trying to make an application that can help me to evaluate the time to download the file from a web resource. I have found 2 samples:
Download与Android的文件,并显示在一个ProgressDialog 进度
和
https://p.xsw88.cn/allimgs/daicuo/20230903/5535.png.jpg"); byte data[] = new byte[1024]; long total = 0; time11 = System.currentTimeMillis(); while ((count = input.read(data)) != -1) { total += count; // publishing the progress.... publishProgress((int)(total*100/lenghtOfFile)); output.write(data, 0, count); } time22= System.currentTimeMillis()-time11; output.flush(); output.close(); input.close(); } catch (Exception e) {} timetaken = System.currentTimeMillis() - time1;
第2 code:
2nd code:
long time1 = System.currentTimeMillis();
DownloadFromUrl(path, "test.jpg");
long timetaken = System.currentTimeMillis() - time1;
其中,
public void DownloadFromUrl(String imageURL, String fileName) { //this is the downloader method
try {
URL url = new URL(imageURL); //you can write here any link
File file = new File(fileName);
/*Open a connection to that URL. */
URLConnection ucon = url.openConnection();
/*
* Define InputStreams to read from the URLConnection.
*/
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
/*
* Read bytes to the Buffer until there is nothing more to read(-1).
*/
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
/* Convert the Bytes read to a String. */
FileOutputStream fos = new FileOutputStream(PATH+file);
fos.write(baf.toByteArray());
fos.close();
} catch (IOException e) {
Log.d("ImageManager", "Error: " + e);
}
所以事情是,第一种方法似乎是慢30%左右。
So the thing is that first method seems to be slower for about 30%.
推荐答案
的的第二个例子可以运行得更快,但它垄断了GUI线程。该第一种方法,使用的 的AsyncTask
,效果较好;它允许GUI留响应作为下载所得。
The second example may run faster, but it monopolizes the GUI thread. The first approach, using AsyncTask
, is better; it allows the GUI to stay responsive as the download proceeds.
我觉得比较有帮助 的AsyncTask
与 的SwingWorker
,如本例如。
I found it helpful to compare AsyncTask
with SwingWorker
, as shown in this example.
相关推荐
最新文章