class MyAccessibilityService : AccessibilityService() {
override fun onServiceConnected() {
super.onServiceConnected()
windowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager
showOverlay()
}
private fun showOverlay() {
// omitted about composeView code
windowManager.addView(composeView, params)
runBlocking(newSingleThreadContext("MyOwnThread")) {
while (true) {
delay(1000 * 10)
windows.forEach { println(it) }
}
}
}
}
为什么在
runBlocking
之后用windowManager.addView
阻塞线程导致浮窗不起作用?
我看不出两者之间有任何联系吗?
你在阻止
onServiceConnected()
返回,因此操作系统甚至无法完成设置并继续其生命周期。
您需要在服务被销毁时取消的范围内运行协程,否则您将永远泄漏所有内容。像这样的东西:
class MyAccessibilityService : AccessibilityService() {
private val lifecycleScope = MainScope() + CoroutineName("MyAccessibilityService lifecycleScope")
override fun onDestroy() {
super.onDestroy()
lifecycleScope.cancel()
}
override fun onServiceConnected() {
super.onServiceConnected()
windowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager
showOverlay()
}
private fun showOverlay() {
// omitted about composeView code
windowManager.addView(composeView, params)
lifecycleScope.launch {
while (true) {
delay(1000 * 10)
windows.forEach { println(it) }
}
}
}
}