为什么我不能在 AsyncTask 的 doInBackground 方法中运行 ProgressDialog?
我无法在 AsyncTask 的 doInBackground
方法中运行 ProgressDialog
。它给了我以下错误:
错误/AndroidRuntime(12986):原因:java.lang.RuntimeException:无法在未调用 Looper.prepare() 的线程内创建处理程序
并且错误位于代码中的这一行:
final ProgressDialog dialog = ProgressDialog.show(GalleryView.this, "Refresh", "Loading... please wait", true);
非常感谢任何帮助。
I am not able to run a ProgressDialog
inside the doInBackground
method of AsyncTask. It gives me the following error:
ERROR/AndroidRuntime(12986): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
And the error is on this line in the code:
final ProgressDialog dialog = ProgressDialog.show(GalleryView.this, "Refresh", "Loading... please wait", true);
Any help much appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以在 onPreExecute 方法中显示进度对话框,并在 onPostExecute 方法中关闭它。这两个方法运行在UI线程中。 doInBackGround 方法在另一个线程中运行。
另一种可能性是在启动 AsyncTask 之前仅显示进度对话框。就我个人而言,我喜欢使用 onPreExecute 和 onPostExecute 的选项。然后,进度对话框就可以很好地链接到 AsyncTask。
You can show the progressdialog in the onPreExecute method and dismiss it in the onPostExecute method. These two methods run in the UI thread. The doInBackGround method runs in another thread.
Another possibility is to just show the progressdialog before you start the AsyncTask. Personally I like the option to use onPreExecute and onPostExecute. The progressdialog is then linked nicely to the AsyncTask.
由于 doinbackground 不在 ui 线程上运行,因此它无法创建 UI 元素。您应该在执行 AsyncTask 之前创建进度对话框。
As the doinbackground doesn't run on the ui thread so it cannot create UI elements. You should create the progress dialog before executing the AsyncTask.
AsyncTask
构造用于分离后台和 UI 线程操作。在doInBrackground
中,您不在 UI 线程中,因此您根本无法执行 UI 相关逻辑。执行此操作的正确位置是在 UI 线程上运行的方法中。我猜测对于您的特定情况,这样的地方将是onPreExecute
。The
AsyncTask
construct is about separating background and UI thread operations. WithindoInBrackground
you are not in the UI thread, so you cannot do UI related logic at all. The right place to do that is in the methods that run on the UI thread. I'm guessing for your particular case such place would beonPreExecute
.ProgressDialog 是 UI 代码,因此它必须发生在事件队列上。 AsyncTask 从事件队列中运行。您可以这样创建进度对话框:
ProgressDialog is UI code, so it must happen on the event queue. AsyncTask runs off the event queue. You can do a progress dialog as such: