我们都知道,android中消息机制主要指的是Handler的工作机制,正常情况下,我们可以在UI线程里面创建一个Handler,默认传入是主线程的对应的Looper,这个时候通常用于更新界面UI。Handler的目的本质是实现线程间的通讯,所以,现在我自己想创建一个接受handler发送消息通知就处理逻辑的线程(类似UI线程)应该怎么做了?通常有以下两种方式:
- 使用普通的线程
- 使用我们今天的HandlerThread
方式1实现如下:
Thread thread=new Thread("Thread-why"){
@Override
public void run() {
Looper.prepare();
threadHandler=new Handler(Looper.myLooper()){
@Override
public void handleMessage(Message msg) {
Log.e(TAG, "threadHandler"+Thread.currentThread().getName());
}
};
Looper.loop();
}
};
这样,我们通过threadHandler发送消息,处理的逻辑将会在“Thread-why”的线程中处理。
方式2实现如下:
subThread.start();//开启线程,启动消息循环
handlerThreadHandler=new Handler(subThread.getLooper()){
@Override
public void handleMessage(Message msg) {
Log.e(TAG, "handlerThreadHandler: "+Thread.currentThread().getName() );
}
};//构建消息处理Handler
其中subThread是Handlerthread的一个实例,这里面相较于方式1来说简化几步,不需要我们手动的调用Looper.prepare()和Looper.loop()。由此,我们猜测在HandlerThread中实现了这样的封装。
下面就来看看HandlerThread的源码(较简单)
/*
* Copyright (C) 2006 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.os;
import android.annotation.NonNull;
import android.annotation.Nullable;
/**
* Handy class for starting a new thread that has a looper. The looper can then be
* used to create handler classes. Note that start() must still be called.
*/
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;
}
/**
* Constructs a HandlerThread.
* @param name
* @param priority The priority to run the thread at. The value supplied must be from
* {@link android.os.Process} and not from java.lang.Thread.
*/
public HandlerThread(String name, int priority) {
super(name);
mPriority = priority;
}
/**
* Call back method that can be explicitly overridden if needed to execute some
* setup before Looper loops.
*/
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;
}
/**
* This method returns the Looper associated with this thread. If this thread not been started
* or for any reason isAlive() returns false, this method will return null. If this thread
* has been started, this method will block until the looper has been initialized.
* @return The looper.
*/
public Looper getLooper() {
if (!isAlive()) {
return null;
}
// If the thread has been started, wait until the looper has been created.
synchronized (this) {
while (isAlive() && mLooper == null) {
try {
wait();
} catch (InterruptedException e) {
}
}
}
return mLooper;
}
/**
* @return a shared {@link Handler} associated with this thread
* @hide
*/
@NonNull
public Handler getThreadHandler() {
if (mHandler == null) {
mHandler = new Handler(getLooper());
}
return mHandler;
}
/**
* Quits the handler thread's looper.
* <p>
* Causes the handler thread's looper to terminate without processing any
* more messages in the message queue.
* </p><p>
* Any attempt to post messages to the queue after the looper is asked to quit will fail.
* For example, the {@link Handler#sendMessage(Message)} method will return false.
* </p><p class="note">
* Using this method may be unsafe because some messages may not be delivered
* before the looper terminates. Consider using {@link #quitSafely} instead to ensure
* that all pending work is completed in an orderly manner.
* </p>
*
* @return True if the looper looper has been asked to quit or false if the
* thread had not yet started running.
*
* @see #quitSafely
*/
public boolean quit() {
Looper looper = getLooper();
if (looper != null) {
looper.quit();
return true;
}
return false;
}
/**
* Quits the handler thread's looper safely.
* <p>
* Causes the handler thread's looper to terminate as soon as all remaining messages
* in the message queue that are already due to be delivered have been handled.
* Pending delayed messages with due times in the future will not be delivered.
* </p><p>
* Any attempt to post messages to the queue after the looper is asked to quit will fail.
* For example, the {@link Handler#sendMessage(Message)} method will return false.
* </p><p>
* If the thread has not been started or has finished (that is if
* {@link #getLooper} returns null), then false is returned.
* Otherwise the looper is asked to quit and true is returned.
* </p>
*
* @return True if the looper looper has been asked to quit or false if the
* thread had not yet started running.
*/
public boolean quitSafely() {
Looper looper = getLooper();
if (looper != null) {
looper.quitSafely();
return true;
}
return false;
}
/**
* Returns the identifier of this thread. See Process.myTid().
*/
public int getThreadId() {
return mTid;
}
}
分几步:
- 简介,从名字以及下面的注释我们可以知道其是一种特殊的线程,自带Looper,通过绑定Handler处理消息
/**
* Handy class for starting a new thread that has a looper. The looper can then be
* used to create handler classes. Note that start() must still be called.
*/
- 注释说,必须执行start(),因为start()继承自Thread,所以只需要看看重写的run()方法即可
@Override
public void run() {
mTid = Process.myTid();
Looper.prepare();
synchronized (this) {
mLooper = Looper.myLooper();
notifyAll();
}
Process.setThreadPriority(mPriority);
onLooperPrepared();
Looper.loop();
mTid = -1;
}
可见,在这里,它完成了我们使用普通Thread创建Handler完成的逻辑。并为与此线程绑定的mLooper赋值,这样我们通过下面就可以获取到一个Looper实例(先判断该线程是否在运行状态,如果是则返回null):
/**
* This method returns the Looper associated with this thread. If this thread not been started
* or for any reason isAlive() returns false, this method will return null. If this thread
* has been started, this method will block until the looper has been initialized.
* @return The looper.
*/
public Looper getLooper() {
if (!isAlive()) {
return null;
}
// If the thread has been started, wait until the looper has been created.
synchronized (this) {
while (isAlive() && mLooper == null) {
try {
wait();
} catch (InterruptedException e) {
}
}
}
return mLooper;
}
可见,HandlerThread是专门为我们使用非UI线程创建Handler处理消息的线程。如果可以,尽量使用方2(HandlerThread),方便安全。下面是一个简单的测试代码:
package aoto.com.operationandroidthread;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
/**
* @author why
* @date 2019-4-13 15:20:34
*/
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivityWhy";
private HandlerThread subThread = new HandlerThread("HandlerThread-Why");//构建可循环处理消息的子线程
private Thread thread;
private Handler handlerThreadHandler;
private Handler threadHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
subThread.start();//开启线程,启动消息循环
handlerThreadHandler = new Handler(subThread.getLooper()) {
@Override
public void handleMessage(Message msg) {
Log.e(TAG, "handlerThreadHandler: " + Thread.currentThread().getName());
}
};//构建消息处理Handler
thread = new Thread("Thread-why") {
@Override
public void run() {
Looper.prepare();
threadHandler = new Handler(Looper.myLooper()) {
@Override
public void handleMessage(Message msg) {
Log.e(TAG, "threadHandler" + Thread.currentThread().getName());
}
};
Looper.loop();
}
};
thread.start();
}
public void testThread(View view) {
threadHandler.sendMessage(Message.obtain());
}
public void sendHandlerThread(View view) {
handlerThreadHandler.sendMessage(Message.obtain());
}
@Override
protected void onDestroy() {
super.onDestroy();
//释放资源
thread.stop();
subThread.quit();
}
}
好了,关于HandlerThread就介绍完了,还是非常简单的,但是比较好用哟。
注:欢迎扫码关注