简体   繁体   English

Android:一个带有两个AsyncTask的ProgressBar

[英]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): 这很简单(不包含代码,仅包含算法):

  1. Start by setting the maximum of your progress to 0. 首先将进度的最大值设置为0。
  2. When any of your asynctasks get their own max value, increment the maximum of the progress by this value. 当您的任何asynctasks获得其自己的最大值时,将进度的最大值增加此值。
  3. Now as each of the asynctasks finish some of their work, increment the progress current value by that amount. 现在,随着每个异步任务完成一些工作,将进度当前值增加该数量。
  4. When all of your asynctasks are done, the amount of work done will sum up to the sum of each asynctask's maximum value and you will get a 100% progress. 完成所有异步任务后,完成的工作量总计为每个异步任务最大值的总和,您将获得100%的进度。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM