getLooper() returns 启动 HandlerThread 后为空
getLooper() returns null after started HandlerThread
我有一个 class extends HandlerThread
,它看起来像这样:
public class MyHandlerThread extends HandlerThread {
private Object lock;
//constructor
public MyHandlerThread() {
super(“MyHandlerThread”);
lock = new Object();
}
public void prepare() {
//starts the handler thread
start();
//Wait for thread starting
Log.d(TAG, "wait for thread starting…");
synchronized (lock) {
try {
lock.wait(5000);
} catch (InterruptedException e) {
Log.e(TAG, "Failed to wait for thread to start");
}
}
//WHY getLooper() returns null here?
if(getLooper() == null) {
Log.d("GET LOOPER NULL!");
}
}
@Override
public void run() {
Log.d("run() begin...");
initializeSomeObjects()
Log.d(“initialise objects done!”);
//Notify that run() finished
synchronized (lock) {
lock.notify();
}
Log.d("run() end!”);
}
}
正如你在上面看到的,prepare()
函数启动线程并等待 run()
完成,然后尝试获取 looper。
在另一个 class 中,我创建了一个 MyHandlerThread
的实例并启动它:
MyHandlerThread myThread = new MyHandlerThread();
myThread.prepare();
控制台中显示的日志:
wait for thread starting…
run() begin...
initialise objects done!
run() end!
GET LOOPER NULL!
为什么在prepare()
函数中调用getLooper()
returnsnull虽然线程已经启动了(run()
是执行)?
HandlerThread
Looper
在 HandlerThread#run()
中初始化。
如果您重写该方法而不调用 super.run()
,则不会执行超类的初始化代码。
我有一个 class extends HandlerThread
,它看起来像这样:
public class MyHandlerThread extends HandlerThread {
private Object lock;
//constructor
public MyHandlerThread() {
super(“MyHandlerThread”);
lock = new Object();
}
public void prepare() {
//starts the handler thread
start();
//Wait for thread starting
Log.d(TAG, "wait for thread starting…");
synchronized (lock) {
try {
lock.wait(5000);
} catch (InterruptedException e) {
Log.e(TAG, "Failed to wait for thread to start");
}
}
//WHY getLooper() returns null here?
if(getLooper() == null) {
Log.d("GET LOOPER NULL!");
}
}
@Override
public void run() {
Log.d("run() begin...");
initializeSomeObjects()
Log.d(“initialise objects done!”);
//Notify that run() finished
synchronized (lock) {
lock.notify();
}
Log.d("run() end!”);
}
}
正如你在上面看到的,prepare()
函数启动线程并等待 run()
完成,然后尝试获取 looper。
在另一个 class 中,我创建了一个 MyHandlerThread
的实例并启动它:
MyHandlerThread myThread = new MyHandlerThread();
myThread.prepare();
控制台中显示的日志:
wait for thread starting…
run() begin...
initialise objects done!
run() end!
GET LOOPER NULL!
为什么在prepare()
函数中调用getLooper()
returnsnull虽然线程已经启动了(run()
是执行)?
HandlerThread
Looper
在 HandlerThread#run()
中初始化。
如果您重写该方法而不调用 super.run()
,则不会执行超类的初始化代码。