本文翻译自:Android basics: running code in the UI thread

In the viewpoint of running code in the UI thread, is there any difference between: 从在UI线程中运行代码的角度来看,之间有什么区别:

MainActivity.this.runOnUiThread(new Runnable() {public void run() {Log.d("UI thread", "I am the UI thread");}
});

or 要么

MainActivity.this.myView.post(new Runnable() {public void run() {Log.d("UI thread", "I am the UI thread");}
});

and

private class BackgroundTask extends AsyncTask<String, Void, Bitmap> {protected void onPostExecute(Bitmap result) {Log.d("UI thread", "I am the UI thread");}
}

#1楼

参考:https://stackoom.com/question/ruuN/Android基础知识-在UI线程中运行代码


#2楼

None of those are precisely the same, though they will all have the same net effect. 这些都不是完全一样的,尽管它们都具有相同的净效应。

The difference between the first and the second is that if you happen to be on the main application thread when executing the code, the first one ( runOnUiThread() ) will execute the Runnable immediately. 第一和第二之间的区别是,如果你碰巧在执行代码时是主要的应用程序线程 ,第一个( runOnUiThread()将执行Runnable马上。 The second one ( post() ) always puts the Runnable at the end of the event queue, even if you are already on the main application thread. 第二个( post() )总是将Runnable放在事件队列的末尾,即使您已经在主应用程序线程上。

The third one, assuming you create and execute an instance of BackgroundTask , will waste a lot of time grabbing a thread out of the thread pool, to execute a default no-op doInBackground() , before eventually doing what amounts to a post() . 第三个,假设您创建并执行BackgroundTask的实例,将浪费大量时间从线程池中获取线程,执行默认的无操作doInBackground() ,然后最终执行相当于post() This is by far the least efficient of the three. 这是三者中效率最低的。 Use AsyncTask if you actually have work to do in a background thread, not just for the use of onPostExecute() . 如果你真的有后台线程的工作,请使用AsyncTask ,而不仅仅是使用onPostExecute()


#3楼

There is a fourth way using Handler 使用Handler的第四种方法

new Handler().post(new Runnable() {@Overridepublic void run() {// Code here will run in UI thread}
});

#4楼

I like the one from HPP comment , it can be used anywhere without any parameter: 我喜欢HPP评论中的那个,它可以在没有任何参数的任何地方使用:

new Handler(Looper.getMainLooper()).post(new Runnable() {@Overridepublic void run() {Log.d("UI thread", "I am the UI thread");}
});

#5楼

The answer by Pomber is acceptable, however I'm not a big fan of creating new objects repeatedly. Pomber的答案是可以接受的,但我并不是反复创建新对象的忠实粉丝。 The best solutions are always the ones that try to mitigate memory hog. 最好的解决方案总是那些试图减轻记忆力的解决方案。 Yes, there is auto garbage collection but memory conservation in a mobile device falls within the confines of best practice. 是的,有自动垃圾收集,但移动设备中的内存保护属于最佳实践范围。 The code below updates a TextView in a service. 下面的代码更新了服务中的TextView。

TextViewUpdater textViewUpdater = new TextViewUpdater();
Handler textViewUpdaterHandler = new Handler(Looper.getMainLooper());
private class TextViewUpdater implements Runnable{private String txt;@Overridepublic void run() {searchResultTextView.setText(txt);}public void setText(String txt){this.txt = txt;}}

It can be used from anywhere like this: 它可以在任何地方使用:

textViewUpdater.setText("Hello");textViewUpdaterHandler.post(textViewUpdater);

#6楼

As of Android P you can use getMainExecutor() : 从Android P开始,您可以使用getMainExecutor()

getMainExecutor().execute(new Runnable() {@Override public void run() {// Code will run on the main thread}
});

From the Android developer docs : 来自Android开发人员文档 :

Return an Executor that will run enqueued tasks on the main thread associated with this context. 返回一个Executor,它将在与此上下文关联的主线程上运行入队任务。 This is the thread used to dispatch calls to application components (activities, services, etc). 这是用于调用应用程序组件(活动,服务等)的调用的线程。

From the CommonsBlog : 来自CommonsBlog :

You can call getMainExecutor() on Context to get an Executor that will execute its jobs on the main application thread. 您可以在Context上调用getMainExecutor()以获取将在主应用程序线程上执行其作业的Executor。 There are other ways of accomplishing this, using Looper and a custom Executor implementation, but this is simpler. 还有其他方法可以实现这一点,使用Looper和自定义Executor实现,但这更简单。

Android基础知识:在UI线程中运行代码相关推荐

  1. android 运行在ui县城,Android基础:在UI线程中运行代码

    Android基础:在UI线程中运行代码 从在UI线程中运行代码的角度来看,在以下方面有什么区别:MainActivity.this.runOnUiThread(new Runnable() { pu ...

  2. java 动态代理 阿bin_Android WebView 的方法只能在 UI 线程中运行

    Android WebView 的方法只能在 UI 线程中运行 Android,WebView,线程 2018.04.25 根据报错信息,Android 的 WebView 所有的方法都只能在 UI ...

  3. spark编程基础--4.2在spark-shell中运行代码

    启动spark-shell Spark2.1.0入门:Spark的安装和使用 通过spark-submit运行程序

  4. android初步ui线程案例,android – 它是一个bug还是一个功能?在某些情况下,可以从未在UI线程上运行的任务访问UI线程...

    developer.android.com说: Only objects running on the UI thread have access to other objects on that t ...

  5. Android官方开发文档Training系列课程中文版:高效显示位图之在非UI线程中处理图片

    原文地址:http://android.xsoftlab.net/training/displaying-bitmaps/process-bitmap.html 我们在上节课Load Large Bi ...

  6. Android 基础知识+app测试权限问题

    Android 基础知识(权限篇)** 前言 ​ Android是一个开源的,基于Linux的移动设备操作系统,主要用于移动设备,如智能手机和平板电脑.Android是由谷歌及其他公司带领的开放手机联 ...

  7. Android基础知识——完善

    首页 下载App × Android基础知识--完善 布鲁马 2016.05.17 10:29* 字数 5478 阅读 2672评论 1喜欢 38 疯狂Android摘要,Android基础知识好乱好 ...

  8. android基础知识

    技术型男 随笔 - 20, 文章 - 0, 评论 - 4, 引用 - 0 android基础知识 1. 前言 1.1. 什么是3G.4G Ÿ 第三代移动通信技术(3rd - Generation),速 ...

  9. Android基础知识笔记

    ## Android基础面试题 (⭐⭐⭐) #### 1.什么是ANR 如何避免它? 答:在Android上,如果你的应用程序有一段时间响应不够灵敏,系统会向用户显示一个对话框,这个对话框称作应 用程 ...

最新文章

  1. ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock'
  2. camel_Apache Camel 2.14中的更多指标
  3. Use Simple Variables and Formulas
  4. 【虚拟化】Linux中安装配置Docker
  5. 【数据库原理及应用】经典题库附答案(14章全)——第四章:关系系统及其优化
  6. C++中的两个知识点
  7. mysql sql执行cmd命令行_命令行执行MySQL的sql文件
  8. winxp系统的驱动可用于win2k吗?_收藏!工业机器人伺服系统常见问题汇总
  9. 通俗易懂的USB协议详解(转)
  10. PHP利用有道智云提供的API接口来翻译字符串
  11. iOS 开发者必知的 75 个工具
  12. 21天Python进阶学习挑战赛打卡------第2天(基础内容)
  13. java 补齐字符串_使用String.format()格式化字符串,java自动补全自增长字符串
  14. Qt小游戏教程之贪吃蛇(带源码)
  15. 目前住院病人主要由护士护理,这样做不仅需要大量护士,而且由于不能随时观察危害病人的病情变化,还可能会延误抢救时机.某医院打算开发一个以计算机为中心的患者监护系统,试写出问题定义,并且分析开发这个系统
  16. Detecting Holes in Point Set Surfaces 笔记
  17. TVS二极管和稳压二极管应用有什么不同点
  18. 【生活随笔】夜色漫步
  19. 钙钛矿Cs2AgBiBr6|三氟乙胺碘F3EAI|4-三氟甲基苯胺溴CF3PhABr
  20. 关于“指定的参数已超出有效值的范围。参数名 utcDate”的解决方案

热门文章

  1. 全面解读:戴尔”未来就绪的存储保障计划” —— SC系列存储60天无理由退货的影响与意义...
  2. ConTeXt 文稿的逻辑结构
  3. 微软职位内部推荐-Senior Network Engineer
  4. javascript(jQuery版)切换tab效果自动切换(转自www.jqueryba.com)
  5. IE与FireFox的不同点(不断更新中..)
  6. Visual C#组件技巧之深入ComboBox美容
  7. An Implemention of Realtime Gobal Illumination
  8. 『ACM C++』 PTA 天梯赛练习集L1 | 048-49
  9. vue引用jquery
  10. [设计模式] 23 访问者模式 visitor Pattern