建立Message對象的時候,有三種方式,分別爲: 1.Message msg = new Message(); 2.Message msg2 = Message.obtain(); 3.Message msg1 = handler1.obtainMessage(); 這三種方式有什麼區別呢?bash
public class MainActivity extends Activity {
private Handler handler1 = new Handler() {
@Override
public void handleMessage(Message msg) {
Toast.makeText(MainActivity.this, "hanlder1", Toast.LENGTH_SHORT).show();
super.handleMessage(msg);
}
};
;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new Runnable() {
@Override
public void run() {
// Message msg = new Message();
// Message msg2 = Message.obtain();
Message msg1 = handler1.obtainMessage();
msg1.arg1 = 1;
handler1.sendMessage(msg1);
}
}).start();
}
}
複製代碼
1)Message msg = new Message();這種就是直接初始化一個Message對象,沒有什麼特別的。 2)Message msg2 = Message.obtain();ide
/**
* Return a new Message instance from the global pool. Allows us to
* avoid allocating new objects in many cases.
*/
public static Message obtain() {
synchronized (sPoolSync) {
if (sPool != null) {
Message m = sPool;
sPool = m.next;
m.next = null;
m.flags = 0; // clear in-use flag
sPoolSize--;
return m;
}
}
return new Message();
}
複製代碼
從註釋能夠得知,從整個Messge池中返回一個新的Message實例,經過obtainMessage能避免重複Message建立對象。 3)Message msg1 = handler1.obtainMessage();oop
public final Message obtainMessage()
{
return Message.obtain(this);
}
複製代碼
public static Message obtain(Handler h) {
Message m = obtain();
m.target = h;
return m;
}
複製代碼
public static Message obtain() {
synchronized (sPoolSync) {
if (sPool != null) {
Message m = sPool;
sPool = m.next;
m.next = null;
m.flags = 0; // clear in-use flag
sPoolSize--;
return m;
}
}
return new Message();
}
複製代碼
能夠看到,第二種跟第三種實際上是同樣的,均可以免重複建立Message對象,因此建議用第二種或者第三種任何一個建立Message對象。 詳細的源碼講解請看下篇:源碼角度講解Android消息處理機制(Handler、Looper、MessageQueue與Message)學習
若有錯誤歡迎指出來,一塊兒學習。 ui