【发布时间】: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()
}
【问题讨论】: