Android启动页Kotlin协程delay函数参数不匹配报错求助
问题修复方案
错误原因
你定义的SPLASH_DISPLAY_LENGTH是Int类型,但kotlinx.coroutines.delay()函数仅接受Long或Duration类型参数,类型不匹配导致了这个报错。
修复步骤及优化代码
- 修正变量类型:将
SPLASH_DISPLAY_LENGTH改为Long类型(添加L后缀) - 替换协程作用域:避免使用
GlobalScope(易引发内存泄漏),改用Android官方推荐的lifecycleScope(需确保项目已引入androidx.lifecycle:lifecycle-runtime-ktx依赖) - 优化启动逻辑:原代码会先等待5秒显示进度条,再等待5秒才跳转(总耗时10秒),可根据需求调整延迟逻辑
修改后的完整代码:
import android.content.Intent import android.os.Bundle import android.view.View import android.widget.ProgressBar import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.lifecycleScope import kotlinx.coroutines.delay import kotlinx.coroutines.launch class SplashScreen : AppCompatActivity() { private lateinit var progressBar: ProgressBar private val SPLASH_DISPLAY_LENGTH = 5000L // 改为Long类型 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.splash_screen) progressBar = findViewById(R.id.progressBar) // 使用lifecycleScope替代GlobalScope lifecycleScope.launch { // 先显示进度条,再等待指定时长后跳转 progressBar.visibility = View.VISIBLE delay(SPLASH_DISPLAY_LENGTH) loadWebView() } } private fun loadWebView() { startActivity(Intent(this, MainActivity::class.java)) finish() } }
额外说明
如果确实需要在IO线程执行加载逻辑,可保留withContext(Dispatchers.IO),但注意delay参数仍需是Long类型:
private suspend fun loadWebView() { withContext(Dispatchers.IO) { // 这里的延迟参数也要确保是Long类型 delay(SPLASH_DISPLAY_LENGTH) // 执行实际的WebView加载逻辑 } startActivity(Intent(this, MainActivity::class.java)) finish() }
内容的提问来源于stack exchange,提问作者RadioTracer
相关产品推荐
相关产品推荐

