導航:首頁 > 操作系統 > android獲取當前線程id

android獲取當前線程id

發布時間:2025-01-09 21:08:28

㈠ 有關Android的Handler的post方法

我們都知道Handler中的post方法,並且也是經常使用它
handler.post(new Runnable(){
@Override
public void run() {
//do something

}});
用它可以更新一個組件的內容,我們也知道Hanlder中也有一個handler.sendMessage(Message msg)方法,這兩個方法有什麼區別呢?先看一下Message類中定義一個私有的變數:Runnable callback;
再來看一下handler.post(Runnable callback)方法的源碼:
public final boolean post(Runnable r) {
return sendMessageDelayed(getPostMessage(r), 0);
}

再看一下sendMessageDelayed的源碼:
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}

這裡面有個關鍵就是方法getPostMessage(r)這個方法,他將Runnable轉成一個Message,他內部到底幹了什麼呢?看一下他的源碼:
private final Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}

這裡面就是將Runnable轉化成一個Message,其他看他的代碼很簡單,就是先獲取一個空消息Message.obtain(),然後將Message中的callback的值設置成Runnable,這時候就了解到了Message中的callback的作用了!
同時也了解一下View.post(Runnable r)方法的作用:看一下實例代碼:
final Button btn = (Button)findViewById(R.id.btn);
btn.post(new Runnable(){
@Override
public void run() {
btn.setText("不是好人");
}
});
}

上面的代碼就是更新btn中的內容,同樣下面的代碼也可以達到這種效果:
Handler handler = new Handler();
final Button btn = (Button)findViewById(R.id.btn);
handler.post(new Runnable(){
@Override
public void run() {
btn.setText("不是好人");
}
});
}

不同是這個是用handler.post方法,一個是用View.post方法,現在來看一下View.post方法的源代碼:
public boolean post(Runnable action) {
Handler handler;
AttachInfo attachInfo = mAttachInfo;
if (attachInfo != null) {
handler = attachInfo.mHandler;
} else {
// Assume that post will succeed later
ViewRootImpl.getRunQueue().post(action);
return true;
}
return handler.post(action);
}

方法中主要的功能代碼就是attachInfo.mHandler,獲取當前線程的hanlder,和我們在一個線程中定義一個Handler的效果是一樣的。

閱讀全文

與android獲取當前線程id相關的資料

熱點內容
linux將文件清空 瀏覽:476
一套前端編譯平台 瀏覽:598
安卓9x用什麼框架 瀏覽:72
萬用表怎樣量壓縮機漏電 瀏覽:548
無線路由器雲登錄伺服器未連接 瀏覽:781
aes是公鑰密碼演算法 瀏覽:698
linuxphp編譯參數 瀏覽:534
安卓手機怎麼永久關閉後台啟動 瀏覽:40
網站phpjavascript 瀏覽:453
64位java內存 瀏覽:418
女程序員學習方法 瀏覽:383
工程數學線性代數pdf 瀏覽:681
提升程序員技術檔次的書 瀏覽:691
python詞雲圖txt格式 瀏覽:968
韓國料理pdf 瀏覽:227
什麼app就能知道自己的臉型 瀏覽:383
准了app月卡可以看什麼 瀏覽:140
雲伺服器開機要開30秒 瀏覽:646
php數組傳遞給js 瀏覽:640
在世紀的轉折點上pdf 瀏覽:857