【问题标题】:How to start a background thread with coroutine on a service?如何在服务上使用协程启动后台线程?
【发布时间】:2021-09-10 08:44:36
【问题描述】:

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

Kotlin 代码(来自here 的 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()
}

【问题讨论】:

    标签: android kotlin service


    【解决方案1】:

    从 LifecycleService 而不是直接从 Service 扩展您的 Service 类。然后您可以访问生命周期 CoroutineScope,您可以从中启动您的协程。

    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
        }
    
        //...
    
    }
    

    但是,我真的不建议在没有阅读基本文档和掌握核心概念的情况下尝试使用协程,例如如何启动协程,以及挂起函数的作用和用途。

    【讨论】:

      猜你喜欢
      • 2023-01-30
      • 1970-01-01
      • 2020-10-15
      • 2013-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多