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的文档包括:
(强调)
这只是措辞古怪的文档,还是存在使我似乎找不到的Looper
或Handler
与Executor
绑定(bind)的方法?
最佳答案
更新:TL; DR
// Check if this thread already has prepared a looper
if (Looper.myLooper() == null) {
Looper.prepare()
}
val threadHandler = Handler(Looper.myLooper())
val messenger = Messenger(threadHandler)
messenger.send(...)
详细答案
如果您想进一步了解正在发生的事情以及每个代码在哪个线程中运行:
// Check if this thread already has prepared a looper
// Running on Original Thread
if (Looper.myLooper() == null) {
Looper.prepare()
}
// Save thread's Looper (1)
// Running on Original Thread
val threadLooper = Looper.myLooper()
Handler(Looper.getMainLooper()).post {
// Do some UI stuff, for instance, show a dialog
// Running on UI Thread
AlertDialog
.Builder(context)
.setTitle("Dialog title")
.setMessage("Dialog message")
.setNegativeButton("Cancel") { _: DialogInterface, _: Int ->
// Use thread's Looper from (1) to notify the original thread
// Running on UI Thread
Handler(threadLooper).post {
// Running on Original Thread
callback?.onCancel()
}
}
.setPositiveButton("Retry") { _: DialogInterface, _: Int ->
// Use thread's Looper from (1) to notify the original thread
// Running on UI Thread
Handler(threadLooper).post {
// Running on Original Thread
callback?.onRetry()
}
}
.show()
}
// Call loop() to start the thread's loop
// Running on Original Thread
Looper.loop()