[英]Android: One ProgressBar with two AsyncTask
i have two AsyncTasks (subclass of MainActivity
) which download some data simaultaniously. 我有两个AsyncTasks(
MainActivity
子类),它们可以同时下载一些数据。 they are called by 他们被称为
new LoadData(url).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
I want them both to update a ProgressBar
but I cant think of a way to setProgress
from two simultaneous threads so that each thread contributes 50% of the progress. 我希望他们俩都更新一个
ProgressBar
但我想不出一种方法, setProgress
从两个同时执行的线程中进行setProgress
,以便每个线程贡献进度的50%。
public class MainActivity extends Activity {
private static double staticvariable = 0;
private ProgressBar progbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progbar = (ProgressBar) findViewById(R.id.progressBar1);
new LoadData("http://stackoverflow.com")
.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
new LoadData("http://stackoverflow.com")
.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
private class LoadData extends AsyncTask<String, Void, String> {
private String weburl;
public LoadData(String url) {
this.weburl = url;
System.out.println("Starting Download");
}
protected String doInBackground(String... params) {
System.out.println("point 1");
URLConnection conn = null;
URL url = null;
try {
url = new URL(weburl);
conn = url.openConnection();
conn.connect();
InputStream in = null;
in = new BufferedInputStream(url.openStream());
int fileSize = conn.getContentLength();
double taskProgress;
int count;
byte buffer[] = new byte[1024];
while ((count = in.read(buffer)) != -1) {
taskProgress = 50 * ((double) count) / ((double) fileSize);
staticvariable += taskProgress;
progbar.setProgress((int) staticvariable);
}
in.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("finished at " + (int) staticvariable + "%");
return null;
}
}
}
I think the solution lies with using a static variable incrementing itself by count/fileSize
as shown above but i get some strange results. 我认为解决方案在于使用如上所述通过
count/fileSize
自身递增的静态变量,但是我得到了一些奇怪的结果。 At the end of each download i print the percent completion to the console i get: 在每次下载结束时,我将完成百分比打印到控制台上,我得到:
finished at 916%
完成于916%
and 和
finished at 926%
完成于926%
I dont have a clue where these numbers are from. 我不知道这些数字是从哪里来的。 Any ideas?
有任何想法吗?
Edit Running only one AsyncTask outputs: 编辑仅运行一个AsyncTask输出:
finished at 447%
完成了447%
It is simple (no code included, just algorithm): 这很简单(不包含代码,仅包含算法):
As a side note, for this to be perfectly perfect, you probably need to set the maximum progress to the sum of each individual maximums before starting the actual work. 附带说明一下,要使其达到完美,您可能需要在开始实际工作之前将最大进度设置为每个最大值的总和。 However, this is a side note and can be discarded.
但是,这是一个旁注,可以丢弃。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.