【发布时间】:2021-11-21 14:25:13
【问题描述】:
1.
我正在使用:
override fun updateNotification(mediaSession: MediaSessionCompat) {
if (!PlayerService.IS_RUNNING) return
GlobalScope.launch {
notificationManager.notify(NOTIFICATION_ID, buildNotification(mediaSession))
}
}
我可以使用:
override fun updateNotification(mediaSession: MediaSessionCompat) {
if (!BeatPlayerService.IS_RUNNING) return
CoroutineScope(Dispatchers.IO).launch {
notificationManager.notify(NOTIFICATION_ID, buildNotification(mediaSession))
}
}
2.
我正在使用:
GlobalScope.launch {
while (true) {
delay(100)
mediaMediaConnection.mediaController ?: continue
val newTime = mediaMediaConnection.mediaController?.playbackState?.position
if (state == BIND_STATE_BOUND) newTime?.toInt()?.let { update(it) }
if (state == BIND_STATE_CANCELED) break
}
}
我可以使用:
CoroutineScope(Dispatchers.IO).launch {
while (true) {
delay(100)
mediaMediaConnection.mediaController ?: continue
val newTime = mediaMediaConnection.mediaController?.playbackState?.position
if (state == BIND_STATE_BOUND) newTime?.toInt()?.let { update(it) }
if (state == BIND_STATE_CANCELED) break
}
}
在我的音乐应用中使用 GlobalScope.launch 与 CoroutineScope().launch 时,我没有发现任何明显的差异。
谁能解释一下在我的1和2
的上下文中哪个更好用我见过:
Why not use GlobalScope.launch?
但不太了解,尤其是在我的用例中。
【问题讨论】:
-
你在哪里有这个第二个代码?在活动/服务中?
-
不,在 viewModel @ArpitShukla
标签: android android-studio kotlin kotlin-coroutines