单独线程更新 UI 中长时间运行的进程

发布于 2024-11-25 07:45:52 字数 466 浏览 1 评论 0原文

我注意到 dot NET 也有类似的问题,但我的问题是针对 Android 的,所以也许解决方案看起来不同。

通过单击按钮激活该过程。该进程作为 UI 线程的一部分运行,最后更新 UI。我添加了进度对话框以更加用户友好,因此我实例化了一个运行该进程的线程,最后它更新 UI 并关闭进度对话框。不幸的是,UI 更新失败,但出现以下异常:

07-19 21:14:04.602: ERROR/Atjeews(283): android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

如果我尝试阻止 UI 线程并在长时间进程完成更新 UI 后释放它,则不会显示进度对话框。我应该尝试在单独的线程中显示进度对话框,还是有另一个更简单的解决方案?

I noticed a similar problem for dot NET, but my problem is for Android, so perhaps solution looks different.

The process is activated by clicking button. The process was running as part of UI thread and at the end it did updating UI. I have added progress dialog to be more user friendly, so I instantiate a thread running the process and at the end it updates UI and dismisses progress dialog. Unfortunately UI update is failing with the exception below:

07-19 21:14:04.602: ERROR/Atjeews(283): android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

If I try to block UI thread and release it after long process finishes to update UI, the progress dialog doesn't get shown. Should I try to show progress dialog in a separate thread instead, or there is another simpler solution?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

最初的梦 2024-12-02 07:45:52

摘自 Android 开发人员进程和线程页面:

为了解决这个问题,Android 提供了多种从其他线程访问 UI 线程的方法。以下是可以提供帮助的方法列表:

Activity.runOnUiThread(可运行)
View.post(可运行)
View.postDelayed(Runnable, long)

您可以实例化一个匿名 Runnable 作为参数,例如 post(new Runnable(){doWhatever();}),它将执行您想要的任何操作而是在 UI 线程上。

Taken from the Android Developers Processes and Threads page:

To fix this problem, Android offers several ways to access the UI thread from other threads. Here is a list of methods that can help:

Activity.runOnUiThread(Runnable)
View.post(Runnable)
View.postDelayed(Runnable, long)

You can just instantiate an anonymous Runnable as the argument, like post(new Runnable(){doWhatever();}), that will do whatever you want on the UI thread instead.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文