Android 编程:我无法从后台线程获取数据并显示进度对话框
抱歉,标题有点难以理解,但我不能 100% 确定要问什么。向您展示代码并看看您是否从中理解会更容易。我在这里找到了使用另一篇文章中的进度对话框的方法,所以这基本上是添加到该文章中。 ( ProgressDialog 在函数完成后才显示 ) 顺便说一句,这是使用带有 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 始终为空,因为 mc 尚未完成工作。因此,如果我这样做,它会完成工作,但不会显示进度对话框。
t.start();
while(t.isAlive());//noop
tmp = mc.getStuff();
任何想法或想法将不胜感激!
Sorry, the title is a bit hard to understand but I'm not 100% sure as to what to ask. its easier to show you the code and see if you understand from that. I found the way to use the progress dialog from another post on here, so this is basically adding onto that post. ( ProgressDialog not showing until after function finishes )
btw, this is using eclipse environment with the android plugin.
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();
now the issue is that tmp is always null because mc isnt finished doing stuff. So, if i do this it finishes doing stuff, but doesnt show the progress dialog..
t.start();
while(t.isAlive());//noop
tmp = mc.getStuff();
Any thoughts or ideas would be greatly appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在第二次尝试中,您使主线程等待新线程完成。
runOnUiThread 调用中的可运行部分是您想要执行的位置 tmp = mc.getStuff();
mc 完成 doStuff() 后,它将在主线程上执行。
但除此之外,请查看blindstuff评论的链接,它简化了线程。
In your second attempt, you are making the main thread wait for the new thread to complete.
The runnable in the runOnUiThread call is where you want to do tmp = mc.getStuff();
That will then be executed on the main thread after mc has finished doStuff().
But otherwise, check out the link blindstuff commented, it simplifies threading.