I am developing an Android app which uses the accessibility service. It has some processing which needs to be executed immediately. But this process freezes the main thread and leads to the app not responding. So, I used kotlin coroutines to do the heavy processing in the background threads. But the problem is that , while it does not freeze the UI, it takes some time to complete. It is not immediate.
How can I do the processing immediately without freezing the UI ?
My code :
class CustomAccessibilityService : AccessibilityService() {
private val accessibilityScope = CoroutineScope(IO)
val accessibilityScopeExceptionhandler = CoroutineExceptionHandler {
context, exception -> Log.wtf(this::class.java.simpleName,"Caught exception. ${exception.message}")
}
override fun onAccessibilityEvent(event: AccessibilityEvent?) {
accessibilityScope.launch(accessibilityScopeExceptionhandler) {
// Some heavy processing.
withContext(Main){
// Take UI actions
}
}
}
}
Everytime an event happens, I get multiple onAccessibilityEvent() callbacks and a coroutine launch happens. So, it takes time to complete.I want to complete the heavy processing immediately.
Are coroutines the best option to achieve my goal ?