【发布时间】:2020-01-08 22:25:26
【问题描述】:
我有一个第三方库,它会定期查询我的视频播放器 (ExoPlayer) 以获取视频中的当前位置等信息。这个第三方库在后台线程上运行。问题是,ExoPlayer 实例不允许被后台线程访问。
我的一个想法是在访问 ExoPlayer 实例之前使用协程强制切换到主线程。像这样的东西(注意这是从多个地方调用的,包括主线程和后台线程):
suspend fun getCurrentPosition(): Long {
if (Looper.myLooper() != Looper.getMainLooper()) {
// On a background thread, switch to main thread and return current position
return withContext(Dispatchers.Main) {
exoPlayerInstance.currentPosition
}
} else {
// Already on main thread, no need to switch threads
return exoPlayerInstance.currentPosition
}
}
然后我会像这样使用 runBlocking 调用它:
runBlocking { videoPlayerWrapper.getCurrentPosition() }
使用runBlocking 是因为第三方库希望立即获得结果。
这有时有效,但有时我的应用程序完全锁定。知道可能出了什么问题吗?任何替代解决方案?
【问题讨论】:
标签: android multithreading kotlin kotlin-coroutines