@@ -22,6 +22,7 @@ import android.os.Handler
22
22
import android.os.HandlerThread
23
23
import android.view.InputDevice
24
24
import androidx.compose.runtime.Composable
25
+ import androidx.compose.runtime.DisposableEffect
25
26
import androidx.compose.runtime.State
26
27
import androidx.compose.runtime.getValue
27
28
import androidx.compose.runtime.remember
@@ -51,7 +52,7 @@ enum class InputDeviceType {
51
52
52
53
class InputDeviceMonitor (
53
54
private var inputManager : InputManager ,
54
- onInputDeviceUpdated : (List <InputDeviceType >) -> Unit
55
+ private val onInputDeviceUpdated : (List <InputDeviceType >) -> Unit
55
56
) : HandlerThread(" InputDeviceMonitor" ) {
56
57
57
58
private lateinit var handler: Handler
@@ -67,31 +68,36 @@ class InputDeviceMonitor(
67
68
override fun onInputDeviceChanged (deviceId : Int ) {
68
69
updateDeviceList()
69
70
}
71
+ }
70
72
71
- private fun updateDeviceList () {
72
- val updatedList = inputManager.inputDeviceIds
73
- .map { deviceId ->
74
- inputManager.getInputDevice(deviceId)
75
- }
76
- .filterNotNull()
77
- .filter { device ->
78
- device.isEnabled && ! device.isVirtual
79
- }
80
- .map { device ->
81
- device.deviceType()
82
- }
83
- .flatten()
84
- .toSet()
85
- .toList()
86
-
87
- onInputDeviceUpdated(updatedList)
88
- }
73
+ private fun updateDeviceList () {
74
+ val updatedList = inputManager.inputDeviceIds
75
+ .map { deviceId ->
76
+ inputManager.getInputDevice(deviceId)
77
+ }
78
+ .filterNotNull()
79
+ .filter { device ->
80
+ device.isEnabled && ! device.isVirtual
81
+ }
82
+ .map { device ->
83
+ device.deviceType()
84
+ }
85
+ .flatten()
86
+ .toSet()
87
+ .toList()
88
+ onInputDeviceUpdated(updatedList)
89
89
}
90
90
91
91
override fun onLooperPrepared () {
92
92
super .onLooperPrepared()
93
93
handler = Handler (looper)
94
94
inputManager.registerInputDeviceListener(listener, handler)
95
+ updateDeviceList()
96
+ }
97
+
98
+ override fun quitSafely (): Boolean {
99
+ inputManager.unregisterInputDeviceListener(listener)
100
+ return super .quitSafely()
95
101
}
96
102
}
97
103
@@ -108,8 +114,14 @@ internal fun rememberInputDeviceMonitor(
108
114
InputDeviceMonitor (
109
115
inputManager = inputManager,
110
116
onInputDeviceUpdated = onInputDeviceUpdated
111
- ).also { monitor ->
117
+ )
118
+ }.also { monitor ->
119
+ DisposableEffect (monitor) {
112
120
monitor.start()
121
+
122
+ onDispose {
123
+ monitor.quitSafely()
124
+ }
113
125
}
114
126
}
115
127
}
0 commit comments