gpt4 book ai didi

android - 我们如何从 Executor 获得 Looper?

转载 作者:行者123 更新时间:2023-12-02 11:16:35 24 4
gpt4 key购买 nike

Google 关于绑定(bind)服务的文档正在推广 using a Messenger in lieu of your own custom binding for IPC .所以,我正在尝试 a particular experiment that I am running .

然而,一个 Messenger需要一个 Handler .如今,一个Handler需要一个 Looper ,在这种情况下我可能想要一个用于后台线程(而不是 Looper.getMainLooper() )。唯一的其他Looper我知道如何获得的是run()一个 HandlerThread并获得 Looper从中。

the deprecated non- Looper forms of the Handler constructor 的文档有:

Implicitly choosing a Looper during Handler construction can lead to bugs where operations are silently lost (if the Handler is not expecting new tasks and quits), crashes (if a handler is sometimes created on a thread without a Looper active), or race conditions, where the thread a handler is associated with is not what the author anticipated. Instead, use an Executor or specify the Looper explicitly, using Looper#getMainLooper, View#getHandler, or similar.



(重点补充)

这只是措辞奇怪的文档,还是有获取 Looper 的方法?或 Handler绑定(bind)到 Executor我似乎找不到?

最佳答案

我认为他们的意思是建议使用 Executor而不是 Handler .我不知道任何ExecutorLooper 支持的实现.

Instead [of a Handler], use an Executor or specify the Looper explicitly, using Looper#getMainLooper, View#getHandler, or similar.



这在您只需要运行 Runable 时很有用。 .例如 CameraManager.openCamera()方法在 API 级别 28 中过载。

The behavior of this method matches that of openCamera(java.lang.String, StateCallback, android.os.Handler), except that it uses Executor as an argument instead of Handler.



如果您需要 Messenger ,您必须始终提供 HanlderLooper 支持,已由 Looper.getMainLooper() 解决, Looper.myLooper()或来自 HandlerThread .

或者,您可以创建一个 Looper并运行 loop() 在上面。但这基本上是 HandlerThread做。

关于android - 我们如何从 Executor 获得 Looper?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60859112/

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