如何在服务上使用协程启动后台线程?

Rif*_*fat 0 service android kotlin

我想启动一个后台线程,它将在服务上执行网络操作。要从onStartCommand自身调用挂起函数,应该挂起,这会删除覆盖。那么启动前台服务执行网络操作的正确方法是什么呢?

Kotlin 代码(Java 代码来自此处):

//Service

override fun onBind(intent: Intent?): IBinder? {
    return null
}

override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {

    val input = intent!!.getStringExtra("inputExtra")
    createNotificationChannel()
    val notificationIntent = Intent(this, MainActivity::class.java)
    val pendingIntent = PendingIntent.getActivity(
        this,
        0, notificationIntent, 0
    )
    val notification: Notification =
        NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("Foreground Service")
            .setContentText(input)
            .setSmallIcon(R.drawable.logo)
            .setContentIntent(pendingIntent)
            .build()
    startForeground(1, notification)

    //How to do something with Coroutine here?

    GlobalScope.run { kotlin.runCatching { } }
    thread() { /* do something */ proceedToUpdate() }

    return START_NOT_STICKY
}

private suspend fun proceedToUpdate(){

    coroutineScope {

    }
}

override fun onDestroy() {
    super.onDestroy()
}
Run Code Online (Sandbox Code Playgroud)

Ten*_*r04 5

Extend your Service class from LifecycleService instead of directly from Service. Then you have access to the lifecycle CoroutineScope, from which you can launch your coroutine.

class MyService: LifecycleService() {

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        //...
        lifecycleScope.launch(Dispatchers.Default) {
            // coroutine code goes in here, for example:
            proceedToUpdate()
        }

        return START_NOT_STICKY
    }

    //...

}
Run Code Online (Sandbox Code Playgroud)

However, I really don't recommend trying to use coroutines without reading the basic documentation and grasping the core concepts, like how you launch a coroutine, and what a suspend function does and what it's for.