【发布时间】:2019-06-05 00:17:59
【问题描述】:
我有两个异步任务。假设A和B。首先执行A,然后在执行后调用B。现在我需要在任务 B 结束后显示进度条。就像从 0 开始的 A 和 100 的 B 结束的百分比。这怎么做?
【问题讨论】:
标签: android asynchronous progress
我有两个异步任务。假设A和B。首先执行A,然后在执行后调用B。现在我需要在任务 B 结束后显示进度条。就像从 0 开始的 A 和 100 的 B 结束的百分比。这怎么做?
【问题讨论】:
标签: android asynchronous progress
在来自 asynctask A 的 onPreExecute 和 onProgressUpdate 中:
@Override
protected void onPreExecute() {
super.onPreExecute();
//show progress bar
}
@Override
protected void onProgressUpdate(Integer... progress) {
ProgressBar.setProgress(progress[0]/2)//we will take only 50% of the progress
}
在您的 onPostExecute 和 onProgressUpdate 在您的异步任务 B 中
@Override
protected void onProgressUpdate(Integer... progress) {
ProgressBar.setProgress(progress[0]/2)//we will take the other 50% of the progress
}
@Override
protected void onPostExecute(String result){
//hide progress here
}
请确保你的进度条是本地的,这样你就可以从两个异步任务中访问它
【讨论】:
在AsyncTasks 内,您可以在onProgressUpdate 或onPostExecute 回调上更新UI。这两个回调在 main (UI) 线程中运行,而 doInBackground 在 worker 线程中运行。
为了使“B”进度条在AsynctaskA完成后显示,我将在AsyncTaskA的onPostExecute回调中启动AsyncTaskB,然后在其@987654329中更新进度条B @回调
public ProgressBar progressBarA = ProgressBar(this); // init with a progress bar coming from the UI here
public ProgressBar progressBarB = ProgressBar(this); // init with a progress bar coming from the UI here
private class AsyncTaskA extends AsyncTask<Void, Integer, Boolean> {
protected Boolean doInBackground(Void... params) {
// do something in the background here
for (int i = 0; i < 100; i++) {
publishProgress(i);
}
return true;
}
protected void onProgressUpdate(Integer... progress) {
progressBarA.setProgress(progress[0]);
}
protected void onPostExecute(Void result) {
AsyncTaskB taskB = new AsyncTaskB();
taskB.execute();
}
}
private class AsyncTaskB extends AsyncTask<Void, Integer, Boolean> {
@Override
protected void onPreExecute() {
super.onPreExecute();
progressBarB.setProgress(0);
}
protected Boolean doInBackground(Void... params) {
// do something in the background here
for (int i = 0; i < 100; i++) {
publishProgress(i);
}
return true;
}
protected void onProgressUpdate(Integer... progress) {
progressBarB.setProgress(progress[0]);
}
protected void onPostExecute(Void result) {
// Toast work complete!
}
}
【讨论】: