導航:首頁 > 操作系統 > 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相關的資料

熱點內容
單片機學習指導 瀏覽:586
胸7椎體輕度壓縮 瀏覽:108
sk5伺服器什麼意思 瀏覽:554
什麼是廊坊交警app 瀏覽:294
衣櫃造價演算法 瀏覽:984
默認的web伺服器地址 瀏覽:694
單片機與發光二極體 瀏覽:320
pythonwebmodule 瀏覽:328
空調壓縮機不停了 瀏覽:115
python序列怎麼取 瀏覽:199
線上資料庫加密怎麼查詢 瀏覽:794
js中數據加密 瀏覽:470
穴pdf 瀏覽:549
阿里雲伺服器雲資料庫還需要嗎 瀏覽:146
在程序設計中常用的演算法有哪些 瀏覽:977
為什麼蘇州公積金app一直維護 瀏覽:805
有ip地址但是dhcp伺服器 瀏覽:446
三星手機加密中斷怎麼回事 瀏覽:538
訓練模型init源碼 瀏覽:840
程序編譯是誰的功能 瀏覽:505