【发布时间】:2020-06-30 20:48:23
【问题描述】:
我花了几个小时追查我的代码丢失线程中断状态的原因,结果发现它实际上是由 Android SDK 中的错误引起的!看看Looper.getLooper()方法:
/**
* 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;
}
请注意,它会吃InterruptedException 而不会重新中断!
既然我知道我的代码没有问题,那么解决这个问题的最佳方法是什么?我是否应该在调用.getLooper() 之前将线程的中断状态存储到一个标志中,然后在调用之后,如果设置了标志,我应该中断自己吗?任何想法将不胜感激:)
【问题讨论】: