gpt4 book ai didi

java - 更新进度对话框

转载 作者:太空狗 更新时间:2023-10-29 12:56:54 31 4
gpt4 key购买 nike

我正在尝试制作一个应用程序来帮助我评估从 Web 资源下载文件的时间。我找到了 2 个样本:

Download a file with Android, and showing the progress in a ProgressDialog

http://www.helloandroid.com/tutorials/how-download-fileimage-url-your-device

第二个示例显示了更短的下载时间,但我无法理解如何使用它来更新进度对话框。我认为在第二种情况下应该用“while”表达式来完成一些事情,但我找不到什么。有人可以给我任何建议吗?

更新:

第一个代码:

try {
time1 = System.currentTimeMillis();
URL url = new URL(path);
URLConnection conexion = url.openConnection();
conexion.connect();
// this will be useful so that you can show a tipical 0-100% progress bar
int lenghtOfFile = conexion.getContentLength();
// downlod the file
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/analyzer/test.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;

第二个代码:

       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%。

最佳答案

second example可能运行得更快,但它独占了 GUI 线程。 first approach , 使用 AsyncTask , 更好;它允许 GUI 在下载过程中保持响应。

我发现比较 AsyncTask 很有帮助与 SwingWorker ,如图所示 example .

关于java - 更新进度对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5524472/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com