AsyncTask onPostExecute 未在主线程上运行?
我的应用程序上有一些访问网络服务的活动。由于我不想占用主线程,因此该代码位于 AsyncTask 中。但是,我不希望用户在调用 Web 服务时操作 Activity,因此在执行 AsyncTask 之前,我会显示一个旋转并阻止屏幕的 ProgressDialog。在 AsyncTask 的 onPostExecute 方法中,我做的第一件事是关闭 ProgressDialog。
这应该可以防止用户在没有实际阻塞主线程的情况下操作 Activity。
但是,我注意到有几次 ProgressDialog 从不被关闭并且用户陷入困境。 AsyncTask 已完成,onPostExcute 已执行,但仍显示 ProgressDialog。 ProgressDialog 不可能被关闭,并且用户会卡在屏幕上。他们唯一的选择是访问 Android 设置应用程序并强制停止我的应用程序。
有谁知道为什么会发生这种情况?我能做什么来修复它?
相关代码:
这是我显示 ProgressDialog 并启动任务的方式:
mProgress = ProgressDialog.show(this, "", "Syncing...", true);
(new MyAsyncTask()).execute(intUserId);
这是任务的 onPostExcute。没有“@Override”
protected void onPostExecute(Boolean result) {
if (mProgress != null) {
mProgress.dismiss();
mProgress = null;
}
}
I have a few Activities on my app that hit a web service. Since I don't want to hold up the main thread, this code is in an AsyncTask. However, I do not want the user to be manipulating the Activity while the web service is being called, so before executing the AsyncTask I show a ProgressDialog which spins and blocks the screen. In the onPostExecute method of the AsyncTask, the first thing I do is dismiss the ProgressDialog.
This should prevent the user from manipulating the Activity without actually blocking the main thread.
However, I've noticed a few times where the ProgressDialog is never dismissed and the user becomes stuck. The AsyncTask has finished, onPostExcute has executed, but the ProgressDialog is still shown. The ProgressDialog has no chance of ever being dismissed and the user is stuck on the screen. Their only option is to visit the Android Settings app and force stop my application.
Does anyone have any idea why this happens? What can I do to fix it?
Relevant code:
This is how I show the ProgressDialog and launch the task:
mProgress = ProgressDialog.show(this, "", "Syncing...", true);
(new MyAsyncTask()).execute(intUserId);
This is the onPostExcute for the task. There is no "@Override"
protected void onPostExecute(Boolean result) {
if (mProgress != null) {
mProgress.dismiss();
mProgress = null;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
检查这一点:
asynctack.execute()
。onPostExcute()
上使用 @Override 以确保其定义正确。Check this:
asynctack.execute()
on UI thread.onPostExcute()
to make sure it's properly defined.也许尝试在 onPreExecute() 方法中显示您的 ProgressDialog?
试一试,看看是否有效。
Maybe try showing your ProgressDialog in the onPreExecute() Method?
Give that a shot and see if it works.
Peter Knego 在 OP 下的评论中发布了以下链接。 CommonsWare 的解决方案似乎运作良好。
后台任务、进度对话框、方向更改 - 是有没有100%有效的解决方案?
Peter Knego posted the following link in a comment under the OP. CommonsWare's solution seems to work well.
Backround task, progress dialog, orientation change - is there any 100% working solution?