【问题标题】:Progress Bar % completed (download) Display in Android进度条完成百分比(下载)在 Android 中显示
【发布时间】:2012-07-16 11:58:39
【问题描述】:

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

【问题讨论】:

标签: android service android-asynctask progress-bar


【解决方案1】:

我更喜欢 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);

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

【讨论】:

  • 嗨,只有一个进度对话框显示。不显示进度。我做了和你说的一样的事情。
  • 这会给你百分比(总 * 100 / 文件长度)。如果有帮助,您可以接受答案。
【解决方案2】:

这样试试

这是一个类

public class XYZ extends Activity {

public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private Button startBtn;
private ProgressDialog mProgressDialog;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    startBtn = (Button)findViewById(R.id.startBtn);
    startBtn.setOnClickListener(new OnClickListener(){
        public void onClick(View v) {
            startDownload();
        }
    });
}

private void startDownload() {
    String url = "http://.jpg";
    new DownloadFileAsync().execute(url);
}
@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case DIALOG_DOWNLOAD_PROGRESS:
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setMessage("Downloading file..");
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mProgressDialog.setCancelable(false);
        mProgressDialog.show();
        return mProgressDialog;
    default:
        return null;
    }
}

类 DownloadFileAsync 扩展 AsyncTask {

@Override
protected void onPreExecute() {
    super.onPreExecute();
    showDialog(DIALOG_DOWNLOAD_PROGRESS);
}

@Override
protected String doInBackground(String... aurl) {
    int count;

try {

URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();

int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);

InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/some_photo_from_gdansk_poland.jpg");

byte data[] = new byte[1024];

long total = 0;

    while ((count = input.read(data)) != -1) {
        total += count;
        publishProgress(""+(int)((total*100)/lenghtOfFile));
        output.write(data, 0, count);
    }

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

}
protected void onProgressUpdate(String... progress) {
     Log.d("ANDRO_ASYNC",progress[0]);
     mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}

@Override
protected void onPostExecute(String unused) {
    dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}

} }

这是一个xml文件

http://pastie.org/4265745

祝你好运 阿米尔汗一世。

【讨论】:

  • 嗨,感谢您的回复。进度还没有显示。我做了和你指定的一样的事情。
【解决方案3】:

带有计数百分比的进度条

//你可以在Firebase Storage上传任务后使用这些方法

 final ProgressDialog progressDialog = new ProgressDialog(this);
   progressDialog.setTitle("Uploading...");
   progressDialog.show();
   progressDialog.setCanceledOnTouchOutside(false);
   StorageReference reference = storageReference
                                  .child("images/" + UUID.randomUUID().toString());

  reference.putFile(filePath).addOnProgressListener(new 
                                OnProgressListener<UploadTask.TaskSnapshot>() {
                                @Override
                                public void onProgress(@NonNull UploadTask.TaskSnapshot 
                                      taskSnapshot) {
                                    double progress =                  
             (100.0*taskSnapshot.getBytesTransferred()/taskSnapshot.getTotalByteCount());
                                    progressDialog.setMessage("Uploaded "+ 
                                 (int)progress+"%");

                                }
                            });

结果

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-28
    • 1970-01-01
    • 2015-11-20
    • 1970-01-01
    相关资源
    最近更新 更多