1、在子线程中直接添加Looper.prepare和Looper.loop,如图:
private void test(){
new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(@NonNull Message msg) {
return false;
}
});
Looper.loop();
}
}).start();
}
但这样创建handler的缺点是,不能像主线程的一样在任何地方都创建handler,因为拿不到子线程的Loop。
改进的办法,可以新建一个子线程的类,在子线程里获取到Loop,通过get拿到。如图:
package com.pwl.myapplication.handlerThreadtest;
import android.os.Looper;
import androidx.annotation.NonNull;
/**
* Created by pwl on 2022/10/28.
*/
public class ThreadTest extends Thread{
Looper looper;
public ThreadTest(@NonNull String name) {
super(name);
}
@Override
public void run() {
super.run();
Looper.prepare();
looper = Looper.myLooper();
Looper.loop();
}
@Override
public synchronized void start() {
super.start();
}
public Looper getLooper() {
return looper;
}
}
private void handlerTest(){
ThreadTest threadTest = new ThreadTest("threadTest");
threadTest.start();
Handler handler1 = new Handler(threadTest.getLooper());
Handler handler2 = new Handler(threadTest.getLooper());
}
但这样做出现的问题是如果子线程没执行完,threadHandler.getLooper()拿到的是null。所以必须让子线程执行完,获取到Loop之后才能执行new Handler(threadHandler.getLooper()),在这里可以用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;
/**
* A {@link Thread} that has a {@link Looper}.
* The {@link Looper} can then be used to create {@link Handler}s.
* <p>
* Note that just like with a regular {@link Thread}, {@link #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;
}
}
这个HandlerThread类用到synchronized、wait、notifyAll解决并发编程的问题。
当我们执行getLooper()时,拿到锁(synchronized),如果此时mLooper==null,则进入while()函数(这里使用while而不用if是因为wait可能会被其他地方的notify唤醒),wait()等待并释放锁,释放锁之后等线程执行到run函数,就可以进入已经释放的锁(synchronized),给mLooper赋值,获取到mLooper后直接notifyAll唤醒wait。
注:wait不会阻塞主线程,主线程程序还可以往下执行,跟sleep不一样。
2、HandlerThread的小实例
模拟一个场景,在子线程进行耗时操作(如下载),结束后给主线程发送消息,主线程收到消息后再给子线程发送消息。
新建一个HandlerThreadTest类
package com.pwl.myapplication.handlerThreadtest;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.util.Log;
import androidx.annotation.NonNull;
/**
* Created by pwl on 2022/10/28.
*/
public class HandlerThreadTest {
private static final String TAG = HandlerThreadTest.class.getSimpleName();
public static final int SEND_TO_UI = 1;//发给UI线程
public static final int SEND_TO_KID = 2;//发给子线程
private HandlerThread mHandlerThread;
private Handler mKidHandler;
private Handler mUIHandler;
public HandlerThreadTest(Handler mUIHandler) {
this.mUIHandler = mUIHandler;
}
public void startDownload(){
mHandlerThread = new HandlerThread("HandlerThread");
mHandlerThread.start();
mKidHandler = new Handler(mHandlerThread.getLooper()){
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
Log.d("TAG", "handleMessage: 在子线程中开始下载");
try {
//耗时操作
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.d("TAG", "handleMessage: 下载结束,给UI线程发消息");
mUIHandler.sendEmptyMessage(SEND_TO_UI);
}
};
sendMessageToKid();
}
//主线程发消息给子线程
public void sendMessageToKid(){
Log.d("TAG", "sendMessageToKid: 发送消息给子线程");
mKidHandler.sendEmptyMessage(SEND_TO_KID);
}
public void quit(){
Log.d("TAG", "quit: 退出");
mHandlerThread.quit();
}
}
在Acitivity中添加如下代码,并执行handlerThreadTest()方法:
private Handler handler = new Handler(){
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
Log.d("TAG", "handleMessage: UI线程收到子线程发送的消息");
mHandlerThreadTest.sendMessageToKid();
}
};
private void handlerThreadTest(){
mHandlerThreadTest = new HandlerThreadTest(handler);
mHandlerThreadTest.startDownload();
}
@Override
protected void onDestroy() {
super.onDestroy();
mHandlerThreadTest.quit();
}
打印log如下:
2022-10-28 15:45:14.232 4591-4591/com.pwl.myapplication D/TAG: sendMessageToKid: 发送消息给子线程
2022-10-28 15:45:14.233 4591-4617/com.pwl.myapplication D/TAG: handleMessage: 开始下载
2022-10-28 15:45:20.234 4591-4617/com.pwl.myapplication D/TAG: handleMessage: 下载结束,给UI线程发消息
2022-10-28 15:45:20.234 4591-4591/com.pwl.myapplication D/TAG: handleMessage: UI线程收到子线程发送的消息
2022-10-28 15:45:20.234 4591-4591/com.pwl.myapplication D/TAG: sendMessageToKid: 发送消息给子线程
2022-10-28 15:45:20.234 4591-4617/com.pwl.myapplication D/TAG: handleMessage: 开始下载
2022-10-28 15:45:26.235 4591-4617/com.pwl.myapplication D/TAG: handleMessage: 下载结束,给UI线程发消息
2022-10-28 15:45:26.235 4591-4591/com.pwl.myapplication D/TAG: handleMessage: UI线程收到子线程发送的消息
2022-10-28 15:45:26.235 4591-4591/com.pwl.myapplication D/TAG: sendMessageToKid: 发送消息给子线程
2022-10-28 15:45:26.235 4591-4617/com.pwl.myapplication D/TAG: handleMessage: 开始下载
2022-10-28 15:45:32.237 4591-4617/com.pwl.myapplication D/TAG: handleMessage: 下载结束,给UI线程发消息
2022-10-28 15:45:32.237 4591-4591/com.pwl.myapplication D/TAG: handleMessage: UI线程收到子线程发送的消息
2022-10-28 15:45:32.237 4591-4591/com.pwl.myapplication D/TAG: sendMessageToKid: 发送消息给子线程
2022-10-28 15:45:32.237 4591-4617/com.pwl.myapplication D/TAG: handleMessage: 开始下载
2022-10-28 15:45:38.240 4591-4617/com.pwl.myapplication D/TAG: handleMessage: 下载结束,给UI线程发消息
2022-10-28 15:45:38.240 4591-4591/com.pwl.myapplication D/TAG: handleMessage: UI线程收到子线程发送的消息
2022-10-28 15:45:38.240 4591-4591/com.pwl.myapplication D/TAG: sendMessageToKid: 发送消息给子线程
2022-10-28 15:45:38.247 4591-4617/com.pwl.myapplication D/TAG: handleMessage: 开始下载
2022-10-28 15:45:38.970 4591-4591/com.pwl.myapplication D/TAG: quit: 退出