gpt4 book ai didi

java - 如何获取我刚刚创建的新线程的 Looper?

转载 作者:行者123 更新时间:2023-12-01 18:55:35 24 4
gpt4 key购买 nike

我正在创建一个线程来处理请求。在线程中,我必须调用 Looper.prepare() ,这是它正在使用的其他一些功能所需要的,然后我调用 Looper.loop() 。但是当请求的连接关闭时,我会在不同的线程中收到回调。此时,我需要在线程的循环器上调用quit(),以便loop()返回并且线程将退出。但是,我很难弄清楚如何获得该线程的循环器。我在 Thread 中没有看到任何获取线程的 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();

并在紧随上述行之后的回调中:

webSocket.setClosedCallback(new CompletedCallback() {
@Override
public void onCompleted(Exception ex) {
// other code
l1.quit();
}
});

我在上面标记的行上收到编译时错误:

Cannot assign a value to final variable 'l1'.

但是我还没有分配它!如果我没有将 Looper 设置为最终的,那么我就无法分配给它,因为它不是最终的。

最佳答案

这看起来有点像黑客,但我创建了这个类(私有(private)的,在同一个文件中):

class LooperHolder {
Looper l1 = null;
void setLooper(Looper looper) {
l1 = looper;
}
Looper getLooper() {
return l1;
}
}

然后我修改了代码以通过活套支架:

            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();

然后在回调中:

Looper l1 = lh.getLooper();
if (l1 != null) l1.quit();

关于java - 如何获取我刚刚创建的新线程的 Looper?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59675340/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com