How do I run a ListenableWorker work on a background thread?

前端 未结 2 692
盖世英雄少女心
盖世英雄少女心 2021-01-03 04:52

Since I need to perform work asynchronously in WorkManager, I need to use the ListenableWorker, which by default runs on the main (UI) thread. Since this work c

2条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-03 05:52

    Well - As the other answers mentioned, if you want to do frequent work (like every 60 sec) you should use foreground service.

    Regardless, I'd use coroutines to get out of the main thread. Like:

            runBlocking(Dispatchers.Default) {
               //If you want to run blocking your code
            }
    

    Or using the GlobalScope Launch

            GlobalScope.launch {
             //Work in a separated thread (running not blocking)
            }
    

    Here is a practical example of getting a location using ListenableWorker and setting up the listeners out of the main thread.

    https://github.com/febaisi/ListenableWorkerExample/blob/master/app/src/main/java/com/febaisi/listenableworkerexample/data/LocationListenableWorker.kt#L28

提交回复
热议问题