gpt4 book ai didi

java - 我们什么时候需要在 android 应用程序中使用 runOnUiThread?

转载 作者:搜寻专家 更新时间:2023-10-30 19:41:07 26 4
gpt4 key购买 nike

我有一个使用此函数运行线程 runOnUiThread 的代码示例。为什么以及何时需要使用它?

编辑

如何使用 AsyncTask 类,优点缺点是什么??

最佳答案

当您想从非 UI 线程更新 UI 时,您必须使用 runOnUiThread()。例如,如果您想从后台线程更新您的用户界面。您也可以使用 Handler 来做同样的事情。

来自文档 -

Runs the specified action on the UI thread. If the current thread is the UI thread, then the action is executed immediately. If the current thread is not the UI thread, the action is posted to the event queue of the UI thread.

语法 -

       Activity_Name.this.runOnUiThread(new Runnable() {

@Override
public void run() {
// your stuff to update the UI

}
});

更新 -

AsyncTask -

If you want to do some Network operation or anything that blocks your UI in that case AsyncTask is best options. There are several other ways for performing the same Background Operations as you can use Service, IntentService also for doing Background Operations. Using AsyncTask will help you doing your UI work and also won't block your UI until your background Operation is going on.

来自文档 -

AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

关于java - 我们什么时候需要在 android 应用程序中使用 runOnUiThread?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10135353/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com