基于suspendCancellableCoroutine的Animator扩展API30崩溃求助
崩溃根因
- API 30及以上版本中,
ViewAnimationUtils.createCircularReveal返回的RenderNodeAnimator修改了cancel()方法的实现逻辑:会直接在调用cancel的当前线程初始化Choreographer,而Choreographer强制要求绑定线程必须有Looper。 - 你的协程启动时指定了
Dispatchers.Default(无Looper的后台工作线程池),当协程被取消时(比如Fragment销毁触发lifecycleScope取消),invokeOnCancellation中注册的cancel()逻辑会直接在后台线程执行,触发The current thread must have a looper异常。 - API 30以下版本的
RenderNodeAnimator.cancel()实现是将取消操作post到主线程队列执行,不会在调用线程直接初始化Choreographer,因此不会触发崩溃。
原有实现的隐性逻辑错误
你将动画完成后的协程恢复逻辑错写在onAnimationStart回调中,正确的回调位置应为onAnimationEnd——当前实现会在动画刚启动时就恢复协程,根本没有实现等待动画完整执行完成的效果。
修复方案
1. 修正后的startAndWait扩展函数
所有和Animator相关的操作(start、cancel、addListener)都强制切到主线程执行,避免后台线程操作UI组件:
suspend fun Animator.startAndWait() = suspendCancellableCoroutine<Unit> { continuation -> val mainHandler = Handler(Looper.getMainLooper()) // 取消回调无论在哪个线程触发,都post到主线程执行cancel continuation.invokeOnCancellation { mainHandler.post { cancel() } } addListener(object : AnimatorListenerAdapter() { private var endedSuccessfully = true override fun onAnimationCancel(animation: Animator?) { endedSuccessfully = false } override fun onAnimationEnd(animation: Animator?) { removeListener(this) if (continuation.isActive) { if (endedSuccessfully) { continuation.resume(Unit) } else { continuation.cancel() } } } }) // start操作也切到主线程执行 mainHandler.post { start() } }
2. 调用侧优化
所有View、Animator操作都要求主线程,不需要手动指定Dispatchers.Default,直接使用lifecycleScope默认的主线程上下文即可,减少不必要的线程切换:
private fun createRevealAnimation() { val x = binding.root.right / 2 val y = binding.root.bottom - binding.root.bottom / 9 val endRadius = hypot(binding.root.width.toDouble(), binding.root.height.toDouble()).toInt() viewLifecycleOwner.lifecycleScope.launch { createCircleRevealAnimator(x, y, endRadius).run { duration = 250 binding.pokeballOpen.visibility = View.VISIBLE startAndWait() navigateToListFragment() } } }
补充说明
- 原有实现能在API30以下运行的原因是旧版Animator框架对调用线程没有强校验,即使在后台线程调用start/cancel也只是将操作post到主线程,不会直接触发Looper检查。
- 修复后的实现完全规避了线程不匹配的问题,同时修正了原逻辑中动画未执行完就恢复协程的bug。
内容的提问来源于stack exchange,提问作者martinseal1987
相关产品推荐
相关产品推荐

