搜尋此網誌

2016年8月8日 星期一

【Android】UI Thread

ref:
https://ptodue.gitbooks.io/book2/content/2.1.2.html
http://ptodue.blogspot.tw/search/label/Runnable
http://ptodue.blogspot.tw/search/label/runOnUiThread

想執行在UI thread,可以呼叫 Activity.runOnUiThread() method。
假設目前的thread已經是在UI thread中,Runnable會立即的去執行。否則會透過UI thread的 MessageQueue 排隊。

new Handler(Looper.getMainLooper()).post(runnable);
以上面例子可以改寫成
Runnable r = new Runnable() {
@Override public void run() {
// Block of code to execute
System.out.println("Runnable run() method executed.")
((Activity) mContext).runOnUiThread(new Runnable() {
public void run() {
//這邊是呼叫main thread handler幫我們處理UI部分
System.out.println("call UI thread to deal with UI part")
}
});
}
};
Thread t = new Thread(r); t.start();
view raw uiThread1.java hosted with ❤ by GitHub

或是改寫成
view.post(new Runnable(){
public void run(){
//update UI
}
});
view raw uiThread2.java hosted with ❤ by GitHub

沒有留言: