2.4 Communicating with the UI Thread
来源:互联网 发布:秘鲁地震预警软件 编辑:程序博客网 时间:2024/05/16 12:22
1. 子线程给UI Thread传message
子线程只需要把message发到UI Thread的message queue中即可。message传到UI Thread是通过UI Thread的Looper操作的,而UI Thread Looper在应用中可以通过Looper.getMainLooper()方法全局访问到,因此使用类似下面的方式就能把子线程的message传到UI Thread:
// 把Task message发到UI ThreadRunnable task = new Runnable() { ... };new Handler(Looper.getMainLooper()).post(task);
2. UI Thread自己内部传message
因为本身是在UI Thread内,默认就是UI Thread Looper,因此可以直接传message
Eg:
// Method called on UI Threadprivate void postFromUiThreadToUiThread() { new Handler().post(new Runnable() { ... }); // The code at this point is part of a message being processed and is executed before the posted message // 翻译:此处的代码也是将被处理的message的一部分,它会在posted message之前被执行。}
3. Activity中使用runOnUiThread()
如果在Activity中执行的话,可以直接调用Activity.runOnUiThread(Runnable)方法。
Eg:
// Method called on UI Theadprivate void postFromUiThreadToUiThread() { runOnUiThread(new Runnable() { ... }); // The code at this point is executed after the message. // 翻译:此处的代码会在message之后被执行。}
注意2和3中new Handler().post()与runOnUiThread()处理message的时间和其之后的代码执行时间顺序的不同之处
4. 自定义一个类似runOnUiThread()方法
因为runOnUiThread()方法只能用在Activity类中,我们在Application子类中自定义一个类似runOnUiThread()的方法,让它把message插入到UI Thread的message queue中。
Eg:
public class MyApplication extends Application { private long mUiThreadId; private Handler mUiHandler; @Override public void onCreate() { super.onCreate(); mUiThreadId = Thread.currentThread().getId(); mUiHandler = new Handler(); } // 自定义一个类似runOnUiThread()的方法 public void customRunOnUiThread(Runnable runnable) { if (Thread.currentThread().getId() != mUiThreadId) { mUiHandler.post(runnable); } else { runnable.run(); } }}
阅读全文
0 0
- 2.4 Communicating with the UI Thread
- Communicating with the UI Thread_翻译
- Communicating with the Debugger
- Fragment Communicating with the Activity
- Communicating with the Database (Using ADO)
- Building a Dynamic UI with Fragments - Communicating with Other Fragments
- error communicating with the remote browser. it may have died.
- Communicating with Other Fragments
- Communicating with Other Fragments
- Building a Dynamic UI with Fragments ---- Communicating with Other Fragme (三)
- 《Training:Communicating with Other Fragments》
- There was a problem communicating with the PayPal servers. Please try again
- unit 5 Communicating with other users
- communicating-with-serial-port-in-C-Sharp
- Protocols for Communicating with Daemons (OS X)
- Communicating with Hardware 《LDD3 学习笔记》
- Android — Communicating with Other Fragments
- Error communicating with MapOutputTracker 问题解析1
- TCP四次挥手后的TIME_WAIT状态
- 中华人民共和国著作权法实施条例(2002)
- nodejs修改代码自动重启-nodemon模块
- C语言-蛇形矩阵
- 前端小白系列——Bootstrap重现捕鱼猎人页面
- 2.4 Communicating with the UI Thread
- 关于javascript的闭包
- Android 屏幕适配方案2
- SQL Server--用户自定义函数
- 让win10死机的JavaScript小代码
- JAVA_基础篇—井字棋盘
- C语言小函数——查找最长数字串
- mysql数据库锁定机制
- 1.java基础细节