android - android runOnUiThread和java中简单代码的区别

标签 android multithreading android-runonuithread

我是 android 应用程序开发的初学者。我在 android 中使用线程。我读过关于在主 UI 上运行代码的 runOnUiThread(如果我没记错的话?我猜。) .

我的问题是主 UI 上的普通代码和 runOnIUThread 中的代码有什么区别。

示例:1

class A
{
getDataFromServer(foo);//Code on mainUI
}

示例:2

getActivity.runOnUiThread(new Runnable(){
@Override
public void run(){
getDataFromServer(foo);
}
});

这两个例子有什么不同。请帮助我。你的回答对我来说将是一个新的学习。

最佳答案

假设您指的是 UIThread 代码的简单代码,

什么是线程?

一个线程定义了一个正在运行的进程

首先 runOnUiThread ..

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.

什么是UIThread

  • 应用程序的主执行线程
  • 您的大部分应用程序代码将在此处运行onCreateonPauseonDestroyonClick、等等

    所以很简单任何导致 UI 更新或更改的事情都必须在 UI 线程上发生

当您显式生成一个新线程在后台工作时,此代码不会在 UIThread 上运行。现在如果您想做一些改变用户界面? 那么欢迎你runOnUiThread

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

关于android - android runOnUiThread和java中简单代码的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41632607/

相关文章:

android - 从已保存状态恢复 View 层次结构不会恢复以编程方式添加的 View

java - Android WebView 完全不尊重 UI 布局

c# - 为什么 Microsoft 的这段示例代码会崩溃?

c++ - 在 QThread 中启动 QTimer

android - 如何对包裹在 `runOnUiThread` 中的代码进行单元测试?

android - 读取所有联系人数据

android - 来自 Android Java 代码的 ionic 电容器处理事件

python - 获取worker返回的数据

java - Android:确保 UI 操作在 UI 线程上完成的最佳实践

android - 通过 UI 或非 UI 线程发送广播?