首页 > 解决方案 > 放置协程后应用程序崩溃 - Android

问题描述

我试图在我的游戏上执行一些代码之前进行延迟。我的代码在没有协同程序的情况下运行得非常好,但是只要我输入:

GlobalScope.launch {
//code
}

或者

GlobalScope.launch {
delay(3000L)
//code
}

该应用程序完全崩溃。奇怪的是,有时它会起作用,有时却不起作用。为什么会这样?

这是堆栈跟踪:

2020-03-14 10:29:18.965 13369-13421/com.example.notagame E/AndroidRuntime: FATAL EXCEPTION: DefaultDispatcher-worker-1
    Process: com.example.notagame, PID: 13369
    android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
        at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:8191)
        at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:1420)
        at android.view.View.requestLayout(View.java:24454)
        at android.view.View.requestLayout(View.java:24454)
        at android.view.View.requestLayout(View.java:24454)
        at android.view.View.requestLayout(View.java:24454)
        at android.view.View.requestLayout(View.java:24454)
        at android.view.View.requestLayout(View.java:24454)
        at androidx.constraintlayout.widget.ConstraintLayout.requestLayout(ConstraintLayout.java:3172)
        at android.view.View.requestLayout(View.java:24454)
        at android.widget.TableLayout.requestLayout(TableLayout.java:228)
        at android.view.View.requestLayout(View.java:24454)
        at android.view.View.requestLayout(View.java:24454)
        at android.view.View.setForeground(View.java:23052)
        at com.example.notagame.Excel$onCreate$1$1.invokeSuspend(Excel.kt:140)
        at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
        at kotlinx.coroutines.DispatchedTask.run(Dispatched.kt:241)
        at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:594)
        at kotlinx.coroutines.scheduling.CoroutineScheduler.access$runSafely(CoroutineScheduler.kt:60)
        at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:740)

标签: androidandroid-studiokotlin

解决方案


推荐阅读