Handler在Thread使用
在子線程中使用handler實(shí)例:
public class MainActivity extends Activity {
private static final String TAG = "MainAty";
@BindView(R.id.tvText)
TextView tvText;
private Handler threadHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
new Thread(
new Runnable() {
@Override
public void run() {
//在子線程中創(chuàng)建handler
Looper.prepare();
threadHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
Log.i(TAG, "threadHandler receive msg");
break;
}
}
};
Looper.loop();
Log.i(TAG, "thread exit");
}
}
, "thread-1").start();
}
@OnClick(R.id.tvText)
public void ClickTextView(){
//子線程創(chuàng)建的handler發(fā)送消息
threadHandler.sendMessage(threadHandler.obtainMessage(1));
}
@Override
protected void onDestroy() {
super.onDestroy();
//退出時(shí)候需要注意Loop還在死循環(huán),需要退出,不然子線程不會(huì)退出
threadHandler.getLooper().quit();
}
}
可以看到,在子線程中創(chuàng)建handler需要注意,首先如果沒有Looper.prepare();
那么直接創(chuàng)建會(huì)拋出異常,異常大概如下
java.lang.RuntimeException: Can't create handler inside thread Thread[thread-1,5,main] that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:205)
此異常跟進(jìn)源碼發(fā)現(xiàn):
public Handler() {
this(null, false);
}
public Handler(Callback callback, boolean async) {
mLooper = Looper.myLooper();
//拋出異常的點(diǎn)
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread " + Thread.currentThread()
+ " that has not called Looper.prepare()");
}
}
那分析Looper.prepare到底干了啥Looper.myLooper:
public static void prepare() {
prepare(true);
}
private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper(quitAllowed));
}
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
Looper.prepare會(huì)new Looper()并且掛在到ThreadLocal上,于是當(dāng)前線程綁定了創(chuàng)建的Looper對(duì)象;而Looper.myLooper就是根據(jù)當(dāng)前線程拿到創(chuàng)建的Looper;
至此如果在子線程創(chuàng)建handler一定需要Looper.prepare;
而Looper.loop()是進(jìn)入一個(gè)死循環(huán)中,保證當(dāng)前線程不會(huì)退出,如果退出了,那發(fā)生的Message消息也沒辦法處理到,源碼位置:
public static void loop() {
...
//死循環(huán),保證不會(huì)退出,否則發(fā)送的handler消息處理不到
for (;;) {
Message msg = queue.next(); // might block
//沒有msg時(shí)候退出
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
...
}
...
}
當(dāng)然這里循環(huán)不會(huì)造成CPU資源過度消耗,因?yàn)閝ueue.next調(diào)用nativePollOnce會(huì)阻塞線程;但如果Activity退出時(shí)候,還是需要將Loop.quit方法去停止死循環(huán),保證不會(huì)內(nèi)存泄露,資源回收及時(shí),如果Loop.quit源碼;
public void quit() {
mQueue.quit(false);
}
void quit(boolean safe) {
...
//移除所有的Message,這樣queue.next == null;
if (safe) {
removeAllFutureMessagesLocked();
} else {
removeAllMessagesLocked();
}
//queue.next調(diào)用nativePollOnce,這里在喚醒
nativeWake(mPtr);
}
}
HandlerThread
Android考慮到子線程實(shí)現(xiàn)這種方式比較繁瑣,因此創(chuàng)建了一個(gè)HandlerThread類:
public class HandlerThreadActivity extends Activity {
private static final String TAG = "HandlerThreadAty";
@BindView(R.id.tvText)
TextView tvText;
private Handler threadHandler;
private HandlerThread thread;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
thread = new HandlerThread("handler-thread");
thread.start();
threadHandler = new Handler(thread.getLooper()){
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
Log.i(TAG, "threadHandler receive msg");
break;
}
}
};
}
@OnClick(R.id.tvText)
public void ClickTextView(){
//子線程創(chuàng)建的threadHandler發(fā)送消息
threadHandler.obtainMessage(1).sendToTarget();
}
@Override
protected void onDestroy() {
super.onDestroy();
//退出時(shí)候需要注意HandlerThread.quit保證退出
thread.quit();
}
}
來分析一波HandlerThread源碼:
public class HandlerThread extends Thread {
int mPriority;
int mTid = -1;
Looper mLooper;
private @Nullable Handler mHandler;
public HandlerThread(String name) {
super(name);
mPriority = Process.THREAD_PRIORITY_DEFAULT;
}
public HandlerThread(String name, int priority) {
super(name);
mPriority = priority;
}
protected void onLooperPrepared() {
}
@Override
public void run() {
mTid = Process.myTid();
Looper.prepare();
synchronized (this) {
mLooper = Looper.myLooper();
notifyAll();
}
Process.setThreadPriority(mPriority);
onLooperPrepared();
Looper.loop();
mTid = -1;
}
public Looper getLooper() {
if (!isAlive()) {
return null;
}
synchronized (this) {
while (isAlive() && mLooper == null) {
try {
wait();
} catch (InterruptedException e) {
}
}
}
return mLooper;
}
@NonNull
public Handler getThreadHandler() {
if (mHandler == null) {
mHandler = new Handler(getLooper());
}
return mHandler;
}
public boolean quit() {
Looper looper = getLooper();
if (looper != null) {
looper.quit();
return true;
}
return false;
}
public boolean quitSafely() {
Looper looper = getLooper();
if (looper != null) {
looper.quitSafely();
return true;
}
return false;
}
public int getThreadId() {
return mTid;
}
}
HandlerThread是繼承Thread,說白了就是一個(gè)單線程,串型執(zhí)行,執(zhí)行效率不高,其中有2個(gè)構(gòu)造方法,
public HandlerThread(String name):只需要指定線程名
public HandlerThread(String name, int priority) :指定線程名和線程優(yōu)先級(jí);
public void run():run方法會(huì)調(diào)用Looper.prepare()將當(dāng)前線程和new Looper綁定在ThreadLocal中,然后Looper.myLooper取出放在mLooper;而getLooper就是返回mLooper,也就是返回HandlerThread線程在run方法創(chuàng)建的那個(gè)Looper對(duì)象;
public Handler getThreadHandler():getThreadHandler這個(gè)方法對(duì)外不公開;
public boolean quit/quitSafely():調(diào)用looper.quit/quitSafely退出;
IntentService
IntentService是由handlerThread+Handler+Service組成
分析其源碼:
public abstract class IntentService extends Service {
private volatile Looper mServiceLooper;
private volatile ServiceHandler mServiceHandler;
private String mName;
private boolean mRedelivery;
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
onHandleIntent((Intent)msg.obj);
stopSelf(msg.arg1);
}
}
public IntentService(String name) {
super();
mName = name;
}
public void setIntentRedelivery(boolean enabled) {
mRedelivery = enabled;
}
@Override
public void onCreate() {
super.onCreate();
HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
@Override
public void onStart(@Nullable Intent intent, int startId) {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}
@Override
public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
onStart(intent, startId);
return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
}
@Override
public void onDestroy() {
mServiceLooper.quit();
}
@Override
@Nullable
public IBinder onBind(Intent intent) {
return null;
}
@WorkerThread
protected abstract void onHandleIntent(@Nullable Intent intent);
}
其在oncreate時(shí)候創(chuàng)建一個(gè)HandlerThread,并且利用HandlerThread線程的Looper創(chuàng)建了一個(gè)mServiceHandler;
ondestory時(shí)候執(zhí)行mServiceLooper.quit()退出Looper的循環(huán);
onStartCommand方法中調(diào)用onStart,在onStart方法中利用mServiceHandler發(fā)送消息,其中msg.arg1會(huì)存startId;
當(dāng)ServiceHandler收到消息,執(zhí)行handleMessage后,調(diào)用onHandleIntent,最后stopSelf(startId);
因此說IntentService一個(gè)異步Service,其onHandleIntent是在子線程中執(zhí)行的,并且執(zhí)行完畢后,會(huì)destory self;
比如startService啟動(dòng)3次,假設(shè)在onStartCommand中startId分別為1,2,3,分別調(diào)用stopself(1),stopself(2),stopself(3);
來看為什么stopself沒有走到onDestory方法,分析源碼:
//Service#stopSelf
public final void stopSelf(int startId) {
...
mActivityManager.stopServiceToken(
new ComponentName(this, mClassName), mToken, startId);
...
}
//AMS#stopServiceToken
@Override
public boolean stopServiceToken(ComponentName className, IBinder token,
int startId) {
synchronized(this) {
return mServices.stopServiceTokenLocked(className, token, startId);
}
}
//AMS#stopServiceTokenLocked
boolean stopServiceTokenLocked(ComponentName className, IBinder token,
int startId) {
ServiceRecord r = findServiceLocked(className, token, UserHandle.getCallingUserId());
if (r != null) {
if (startId >= 0) {
...
//這里判斷如果上次startId和這次stop的startId不等,直接退出
if (r.getLastStartId() != startId) {
return false;
}
...
}
...
//真正StopService的地方
bringDownServiceIfNeededLocked(r, false, false);
...
return true;
}
return false;
}
因此startId分別啟動(dòng)1,2,3時(shí)候,mLastStartId = 3,只有調(diào)用stopSelf(3)時(shí)候才會(huì)進(jìn)入到onDestory生命周期;
這里需要注意如下幾點(diǎn):
IntentService只有一個(gè)線程,如果多次start,onCreate只會(huì)執(zhí)行一次,onStartCommand會(huì)執(zhí)行多次,那handler發(fā)送的消息會(huì)有多個(gè),消息隊(duì)列會(huì)依次執(zhí)行回調(diào)onHandleIntent,等所有消息都依次分發(fā)執(zhí)行完畢后,執(zhí)行完后最后調(diào)用到onDestory生命周期,kill self;此外只能通過startService啟動(dòng),不能通過bindService啟動(dòng),原因是生命周期onStartCommand不會(huì)在bindService中回調(diào);