Android编程:我无法从后台线程获取数据并显示进度对话框

时间:2011-11-08 14:10:04

标签: android progressdialog

对不起,标题有点难以理解,但我不是百分之百确定要问什么。它更容易向您展示代码,看看您是否从中理解。我找到了在这里使用其他帖子的进度对话框的方法,所以这基本上是添加到该帖子上的。 (ProgressDialog not showing until after function finishes) 顺便说一句,这是使用Android插件的eclipse环境。

            final MyClass mc = new MyClass(text,info, this);
            final ProgressDialog dialog = ProgressDialog.show(this, "", "Loading. Please wait...", true);

            Thread t = new Thread(new Runnable() 
            {            
                public void run() 
                {
                    // keep sure that this operations
                    // are thread-safe!
                    Looper.prepare(); //I had to include this to prevent force close error

                    mc.doStuff();//does ALOT of stuff and takes about 30 seconds to complete... which is why i want it in a seperate thread

                    runOnUiThread(new Runnable() 
                    {                    
                        @Override
                        public void run() {
                            if(dialog.isShowing())
                                dialog.dismiss();

                        }
                    });
                }
            });
            t.start();

            tmp = mc.getStuff();

现在问题是tmp总是为null,因为mc没有完成任务。所以,如果我这样做它完成了做的事情,但没有显示进度对话框..

            t.start();
            while(t.isAlive());//noop
            tmp = mc.getStuff();

任何想法或想法将不胜感激!

1 个答案:

答案 0 :(得分:1)

在第二次尝试中,您正在使主线程等待新线程完成。

runOnUiThread调用中的runnable是你想要做的事情tmp = mc.getStuff(); 然后在mc完成doStuff()之后在主线程上执行。

但是否则,请查看blindstuff评论的链接,它简化了线程。