Handler的一般做法
public class MainActivity extends Activity {
//Demo展示,并未考虑内存泄漏等
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
}
};
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new Thread(new Runnable() {
@Override
public void run() {
// Message message = new Message();
Message message = Message.obtain();//更加推荐这种用法
message.arg1 = 10086;
handler.sendMessage(message);
}
}).start();
}
}
解析
解析直接注释在下文源码中,
```
public final class Message implements Parcelable {
Message next;
private static final Object sPoolSync = new Object();
private static Message sPool;
private static int sPoolSize = 0;
/**
*1. sPool是static的
*2. 如果sPool中不为空,则不new Message,而是从pool中去取
*/
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
public void recycle() {
if (isInUse()) {
if (gCheckRecycle) {
throw new IllegalStateException("This message cannot be recycled because it "
+ "is still in use.");
}
return;
}
recycleUnchecked();
}
//回收Message对象的时候,只是清空Message里面的内容,并且添加到sPool中去,以便下次复用
void recycleUnchecked() {
// Mark the message as in use while it remains in the recycled object pool.
// Clear out all other details.
flags = FLAG_IN_USE;
what = 0;
arg1 = 0;
arg2 = 0;
obj = null;
replyTo = null;
sendingUid = -1;
when = 0;
target = null;
callback = null;
data = null;
synchronized (sPoolSync) {
if (sPoolSize < MAX_POOL_SIZE) {
//把当前Message添加到sPool首位
next = sPool;
sPool = this;
sPoolSize++;
}
}
}
}
```
总结:
使用Message.obtain()
的好处是Message
对象可以重复使用,可以免除一直new Message
对象造成无谓的内存压力(不断新建销毁对象),
其他:
查看handler.sendEmptyMessage(10086);
源码也可以看到,内部使用的就是obtain
方法.说明这也是Google
官方推荐的方式.
public class Handler {
public final boolean sendEmptyMessage(int what){
return sendEmptyMessageDelayed(what, 0);
}
public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
Message msg = Message.obtain();//内部也是使用 obtain的方法实现的
msg.what = what;
return sendMessageDelayed(msg, delayMillis);
}
}
网友评论