我是 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
- 应用程序的主执行线程
您的大部分应用程序代码将在此处运行
onCreate
、onPause
、onDestroy
、onClick
、等等所以很简单任何导致 UI 更新或更改的事情都必须在 UI 线程上发生
当您显式生成一个新线程在后台工作时,此代码不会在 UIThread 上运行。现在如果您想做一些改变用户界面?
那么欢迎你runOnUiThread
当您想从非 UI 线程更新 UI 时,您必须使用 runOnUiThread()
。例如,如果您想从后台线程更新您的用户界面。您也可以使用 Handler
来做同样的事情。
关于android - android runOnUiThread和java中简单代码的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41632607/