[英]How do I get the Looper for a new Thread that I just created?
I'm creating a thread to handle a request.我正在创建一个线程来处理请求。 In the thread I must call
Looper.prepare()
which is require by some other functionality it is using, and then I call Looper.loop()
.在线程中,我必须调用
Looper.prepare()
,这是它正在使用的其他一些功能所需要的,然后我调用Looper.loop()
。 But when the connection for the request is closed, I get a callback in a different thread.但是当请求的连接关闭时,我会在不同的线程中收到回调。 At that point I need to call
quit()
on the Thread's looper so that loop() will return and the thread will exit.那时我需要在线程的循环器上调用
quit()
以便 loop() 将返回并且线程将退出。 However, I am having a hard time figuring out how to get that thread's looper.但是,我很难弄清楚如何获得该线程的循环器。 I don't see any in
Thread
to get the Looper for the thread.我在
Thread
没有看到任何可以获取Thread
的 Looper。 In the Looper
class I see a way to get the looper for the current class, but I'm not able to pass this information from the inner class of the Thread to the class that creates it:在
Looper
类中,我看到了一种获取当前类的Looper
的方法,但是我无法将此信息从 Thread 的内部类传递给创建它的类:
final Looper l1;
final Thread thread = new Thread() {
@Override
public void run() {
Looper.prepare();
l1 = Looper.myLooper(); // ERROR!
// initialization goes here
Looper.loop();
Log.d(logtag,"The request thread is done.");
}
};
thread.start();
and in the callback which immediately follows the above line:并在紧随上述行之后的回调中:
webSocket.setClosedCallback(new CompletedCallback() {
@Override
public void onCompleted(Exception ex) {
// other code
l1.quit();
}
});
I get a compile time error on the line marked above:我在上面标记的行上收到编译时错误:
Cannot assign a value to final variable 'l1'.
But I haven't assigned it yet!但是我还没分配呢! If I don't make
Looper
final, then I can't assign to it because it's not final.如果我不让
Looper
最终版本,那么我就不能分配给它,因为它不是最终版本。
This seems like somewhat of a hack, but I created this class (private, in the same file):这看起来有点像黑客,但我创建了这个类(私有的,在同一个文件中):
class LooperHolder {
Looper l1 = null;
void setLooper(Looper looper) {
l1 = looper;
}
Looper getLooper() {
return l1;
}
}
Then I modified my code to go through the looper holder:然后我修改了我的代码以通过活套支架:
final LooperHolder lh = new LooperHolder();
final Thread thread = new Thread() {
@Override
public void run() {
Looper.prepare();
lh.setLooper(Looper.myLooper());
// initialization goes here
Looper.loop();
Log.d(logtag,"The request thread is done.");
}
};
thread.start();
And then in the callback:然后在回调中:
Looper l1 = lh.getLooper();
if (l1 != null) l1.quit();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.