进度栏显示下载完成百分比时出现问题。我有一个服务类,可以在其中进行下载。我可以从此类中获得下载的开始时间和结束时间。在主要活动中,单击按钮后,我必须显示进度%。我听说可以通过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");


这是AsyncTask

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,请参阅此问题。

编辑

完成的百分比是您实际在进度对话框中发布的百分比。如果要显示百分比,则可以使用此百分比(总计* 100 / fileLength)。

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


使用此代码在所需的文本视图中显示百分比。

10-07 19:20
查看更多