android runOnUiThread 与 java 中简单代码的区别

Difference between android runOnUiThread and simple code in java

我是 android 应用程序的初学者 development.I 正在使用 android.I 中的线程已经阅读了 runOnUiThread 主 运行 代码=35=](如果我没记错的话?我猜。)

我的问题是 main UI 上的普通代码和 runOnIUThread.

中的代码有什么区别

示例:1

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

示例:2

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

两者有什么区别example.Please帮助me.Your回复对我来说将是一个新的学习。

通常您的代码在 UI 线程上执行。对于需要较长时间的任务(例如网络请求等...),您将使用后台任务(Handler、AsyncTask、Thread...)。

由于您的视图只能从 UI 线程中 touched,如果您在后台线程中执行代码并且需要,则使用 runOnUiThread()从这个后台线程更新您的观点。

为了解释 'why' Android 有 'runOnUiThread()' 选项,重要的是要理解 java 仅用于创建 Android 使用。 phone 上的代码 运行ning 不是 java。

此外,Android 个线程 'can' 有一个叫做 'looper' 的东西。 'looper' 是通过队列按顺序处理 'tasks(technically runnables and messages)' 的。 'main ui thread' 默认情况下已经附加了一个循环器。

这意味着您创建的 运行nable 已放入主 UI 线程的循环程序队列中。 (这就是为什么 运行nable 不是立即 运行,而是 运行 'quickly'/'soon')

您在 UI 线程上使用 运行nable to 运行 代码的原因是因为您在您创建的其他 'background thread' 中.. . 并想以某种方式更新 UI。 (只有 UI 线程可以与 UI 交互)

假设您指的是 UI线程代码的简单代码,

什么是线程?

一个线程定义一个进程运行ning

首先运行OnUiThread..

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.

什么是UI线程

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

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

当你显式生成一个新线程在后台工作时,这段代码不是运行 UIThread.Now 如果您想做一些改变 UI 的事情怎么办? 那么欢迎你runOnUiThread

当您想从 Non-UI 主题更新您的 UI 时,您必须使用 runOnUiThread()。例如,如果您想从后台线程更新 UI。您也可以使用 Handler 做同样的事情。