android - 进度条 % 已完成(下载)在 Android 中显示

标签 android service android-asynctask progress-bar

我在进度条显示下载完成百分比时遇到问题。我有一个进行下载的服务类。我可以从这个类中获取下载的开始时间和结束时间。在主 Activity 中,单击按钮时我必须显示进度%。我听说可以通过 AsyncTask 实现,但我不知道它是如何工作的。请帮助我提供一些与此相关的示例代码示例。谢谢

最佳答案

为此我更喜欢 AsyncTask。

这是一个例子

ProgressDialog mProgressDialog;
// instantiate it within the onCreate method
mProgressDialog = new ProgressDialog(YourActivity.this);
mProgressDialog.setMessage("A message");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

// execute this when the downloader must be fired
DownloadFile downloadFile = new DownloadFile();
downloadFile.execute("the url to the file you want to download");

这是异步任务

private class DownloadFile extends AsyncTask<String, Integer, String> {
@Override
protected String doInBackground(String... sUrl) {
    try {
        URL url = new URL(sUrl[0]);
        URLConnection connection = url.openConnection();
        connection.connect();
        // this will be useful so that you can show a typical 0-100% progress bar
        int fileLength = connection.getContentLength();

        // download the file
        InputStream input = new BufferedInputStream(url.openStream());
        OutputStream output = new FileOutputStream("/sdcard/file_name.extension");

        byte data[] = new byte[1024];
        long total = 0;
        int count;
        while ((count = input.read(data)) != -1) {
            total += count;
            // publishing the progress....
            publishProgress((int) (total * 100 / fileLength));
            output.write(data, 0, count);
        }

        output.flush();
        output.close();
        input.close();
    } catch (Exception e) {
    }
    return null;
}

这可以使用从服务下载以及下载管理器类来完成。请参阅此问题 details .

编辑

完成的百分比是您在进度对话框中实际发布的百分比。如果你想显示百分比,你可以使用这个(total * 100/fileLength)。

int percentage =  (total * 100 / fileLength);
TextView tv = (TextView)findViewById(R.id.textview);
tv.setText("" + percentage);

使用此代码在所需的 TextView 中显示百分比。

关于android - 进度条 % 已完成(下载)在 Android 中显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11503791/

相关文章:

templates - GRAILS:我可以从 _FORM.GSP 模板调用服务逻辑吗?

android - RxJava 和 Android 服务

安卓异步任务 : what is difference between execute() and get()?

java - 使用 AsyncTask,但遇到意外行为

Android 调试无法工作 XSLT 错误

java - 如何将 bundle 数据从一个 fragment 获取到另一个 fragment ?

android - 如果我在 onResume 中调用 getMeasuredWidth() 或 getWidth() 进行布局,它们会返回 0

java - EMDK 安卓工作室

wcf - WCF 中的异常安全上下文 token

java - Android 上的 Http Url 连接问题抛出 java.lang.IllegalStateException : Already connected