Android的:一个进度条带两个的AsyncTask [英] Android: One ProgressBar with two AsyncTask

查看:184
本文介绍了Android的:一个进度条带两个的AsyncTask的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个AsyncTasks其中simaultaniously下载一些数据( MainActivity 的子类)。它们是由

称为

新LoadData(URL).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

我希望他们都更新进度,但我不能从两个并发线程想办法 setProgress 以便每个线程贡献的进展的50%。

 公共类MainActivity延伸活动{
    私有静态双staticvariable = 0;
    私人进度progbar;    @覆盖
    保护无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.activity_main);
        progbar =(进度)findViewById(R.id.progressBar1);        新LoadData(http://stackoverflow.com)
                .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        新LoadData(http://stackoverflow.com)
                .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }    私有类LoadData扩展的AsyncTask<弦乐,太虚,字符串> {
        私人字符串WEBURL;        公共LoadData(字符串URL){
            this.weburl =网址;
            的System.out.println(开始下载);
        }        保护字符串doInBackground(字符串... PARAMS){
            的System.out.println(点1);
            康涅狄格州的URLConnection = NULL;
            网址URL = NULL;
            尝试{
                URL =新的URL(WEBURL);
                康恩= url.openConnection();
                conn.connect();
                在的InputStream = NULL;
                在=新的BufferedInputStream(url.openStream());
                INT档案大小= conn.getContentLength();
                双taskProgress;
                诠释计数;
                字节的缓冲区[] =新的字节[1024];
                而((计数= in.read(缓冲液))!= - 1){
                    taskProgress = 50 *((双)数)/((双)文件大小);
                    staticvariable + = taskProgress;
                    progbar.setProgress((INT)staticvariable);
                }
                附寄();
            }赶上(MalformedURLException的E){
                e.printStackTrace();
            }赶上(IOException异常五){
                e.printStackTrace();
            }            的System.out.println(+(INT)staticvariable +%,在完成了);
            返回null;        }
    }
}

我认为解决的办法是用一个静态变量递增本身计数/档案大小如上所示,但我得到一些奇怪的结果。在每次下载结束时,我打印完成到控制台我得到百分比:


  

在916%完成



  

926%完成


我没有一个线索在哪里,这些数字是从。任何想法?


修改
只运行一个AsyncTask的输出:


  

在447%完成



解决方案

这是简单(没有code在内,只是算法):


  1. 由最大的进度设置为0开始。

  2. 当你的任何asynctasks的获得自己的最大值,增量最大的该值的进展。

  3. 现在,因为每个asynctasks的完成一些工作的关系,通过量增加的进展电流值。

  4. 当你所有的asynctasks的都做了,做的工作量将总结每个AsyncTask的最大值的总和,你会得到100%的进度。


作为一个方面说明,这是完全完美的,你可能需要开始实际工作之前设置到每一个人最大值的总和的最大进步。然而,这是一个方面说明,并且可以被丢弃。

i have two AsyncTasks (subclass of MainActivity) which download some data simaultaniously. 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.

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. At the end of each download i print the percent completion to the console i get:

finished at 916%

and

finished at 926%

I dont have a clue where these numbers are from. Any ideas?


Edit Running only one AsyncTask outputs:

finished at 447%

解决方案

It is simple (no code included, just algorithm):

  1. Start by setting the maximum of your progress to 0.
  2. When any of your asynctasks get their own max value, increment the maximum of the progress by this value.
  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.


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.

这篇关于Android的:一个进度条带两个的AsyncTask的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆