Android ProgressDialog运行时异常错误
我在尝试将 ProgressDialog 放入我的应用程序时遇到问题。在我的 GameEngine 类(不扩展任何内容)中,我有下面所示的代码。第一行产生一个运行时异常,尽管我遇到了这个似乎与相同错误大致相同的线程: -show-progressdialog-is-added-in-run">如果在run()中添加Show ProgressDialog,Android TimerTask会抛出RuntimeException,我不太明白如何实现该解决方案。任何帮助将不胜感激,谢谢。
//Create ProgressDialog
ProgressDialog dialog = ProgressDialog.show(context, "",
"Loading...", true);
//Set Clusters before level starts
for (int i = 0; i < 80; i++)
{
updateBacteria();
updateAttraction();
checkCollisions();
moveObjectsAwayFromWalls();
}
dialog.dismiss();
I'm having trouble trying to put a ProgressDialog into my app. In my GameEngine class (which doesn't extend anything), I have the code shown below. The first line produces a runtime exception, and although I came across this thread that seems to be about the same error: Android TimerTask throws RuntimeException if Show ProgressDialog is added in run(), I don't really understand how to implement the solution. Any help would be much appreciated, thanks.
//Create ProgressDialog
ProgressDialog dialog = ProgressDialog.show(context, "",
"Loading...", true);
//Set Clusters before level starts
for (int i = 0; i < 80; i++)
{
updateBacteria();
updateAttraction();
checkCollisions();
moveObjectsAwayFromWalls();
}
dialog.dismiss();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您只能在 UI 线程(这是扩展 Activity 的主类)中显示对话框。为此,您可以编写一个 Handler 并使用它从非 UI 线程向 UI 线程发送消息。 Android 在 其 ProgressDialog 示例中提供了一个示例。 查看他们在“带有第二个线程的示例 ProgressDialog”下的代码片段。
尽管处理程序是一种更强大的方法,但您也可以遵循您提供的链接的答案中所写的相同方法。
You can only show dialogs in the UI thread (which is your main class which extends Activity). To be able to do this, you can write a
Handler
and use it to send messages from the non UI thread to the UI thread. Android have an example of this in their ProgressDialog example. View the snippet of code they have under "Example ProgressDialog with a second thread".You can also follow the same method as written in the answer of the link you provided, although a Handler is a more robust approach.
如果此方法未在您的主活动线程中运行,您应该更改它。如何?在主活动中设置一个处理程序并将其传递给线程(上面)。在 handler 中,您应该实现方法中与 GUI 相关的部分(即
进度对话框
)。当您需要显示ProgressDialog
时,只需调用您的Handler
并继续处理(在本例中为循环)。与dismiss()
相同。If this method is not running in your Main Activity thread, you should change it. how? Set a Handler in the main activity and pass it to the thread (above). In the handler you should implement the GUI related part of your method (i.e.
ProgressDialog
). When you need to show theProgressDialog
, just call yourHandler
and than keep processing (your loop in this case). Same for thedismiss()
.