Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android線程間通信

Android線程間通信

編輯:關於Android編程

Android采用UI單線程模型,所以工作線程(非UI線程)與UI線程的通信是不可避免的。工作線程與UI主線程通信(進行更新UI等操作)主要有以下三種方式。

First :

Looper.getMainLooper()


Runnable task = getTask();

new Handler(Looper.getMainLooper()).post(task);


Second :

Activity#runOnUiThread()


Runnable task = getTask();

runOnUiThread(task);


The implements of runOnUiThread is shown as bellow :

public final void runOnUiThread(Runnable action) {
if (Thread.currentThread() != mUiThread) {
mHandler.post(action);
} else {
action.run();
}
}
It will check if the current Thread is already the UI thread and then execute it directly. Posting it as a message will delay the execution until you return from the current UI-thread method.


Third:

There is also a third way to execute a Runnable on the UI thread which would be View#post(Runnable) - this one will always post the message even when called from the UI thread. That is useful since that will ensure that the View has been properly constructed and has a layout before the code is executed.

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved