Kotlin:runBlocking导致App应用出现ANR问题实例

runBlocking简介

runBlocking 是常规函数;

runBlocking 方法会阻塞当前线程来等待;

runBlocking 的主线程会一直 阻塞 直到 runBlocking 内部的协程执行完毕。

runBlocking导致App应用出现ANR问题实例的效果

点击页面上的 刷新按钮 调用 refreshByrunBlocking方法,此方法里模拟了等待30秒耗时操作,当点击 刷新按钮 等待3秒左右,点击 详情按钮 ,页面出现ANR弹框如下图所示

页面布局activity_test_anr_by_runblocking.xml代码

bash 复制代码
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/btn_refresh"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="60dp"
        android:layout_marginRight="20dp"
        android:gravity="center"
        android:onClick="onClick"
        android:text="刷新"
        android:textColor="@color/black"
        android:textSize="20sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btn_detail"
        android:layout_width="0dp"
        android:layout_height="50dp"
        android:layout_marginTop="60dp"
        android:gravity="center"
        android:onClick="onClick"
        android:text="详情"
        android:textColor="@color/black"
        android:textSize="20sp"
        app:layout_constraintLeft_toLeftOf="@+id/btn_refresh"
        app:layout_constraintRight_toRightOf="@+id/btn_refresh"
        app:layout_constraintTop_toBottomOf="@+id/btn_refresh" />

    <TextView
        android:id="@+id/tv_detail"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="60dp"
        android:onClick="onClick"
        android:textColor="@color/black"
        android:textSize="16sp"
        app:layout_constraintLeft_toLeftOf="@+id/btn_detail"
        app:layout_constraintRight_toRightOf="@+id/btn_detail"
        app:layout_constraintTop_toBottomOf="@+id/btn_detail"
        tools:text="用户信息" />


</androidx.constraintlayout.widget.ConstraintLayout>

实体类:PsersonBean.kt代码

bash 复制代码
data class PsersonBean(val name: String, var moblie: String? = null)//至少有一个构造函数

TestANRByRunBlockingActivity.kt代码

bash 复制代码
package example.demo.kotlin.activity

import android.app.Activity
import android.os.Bundle
import android.view.View
import android.widget.TextView
import example.demo.kotlin.R
import example.demo.kotlin.bean.PsersonBean
import example.demo.kotlin.utils.LogUtil
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking


class TestANRByRunBlockingActivity : Activity() {
    private lateinit var tv_detail: TextView
    private var psersonBean: PsersonBean

    init {
        psersonBean = PsersonBean("测试用户01")
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_test_anr_by_runblocking)
        initView()
    }

    override fun onStart() {
        super.onStart()
        showData()
    }

    fun initView() {
        tv_detail = findViewById(R.id.tv_detail)
    }

    fun showData() {
        //使用lateinit var 延时初始化,这里安全起见,判断是否 isInitialized
        if (::tv_detail.isInitialized) {
            tv_detail.setText("$psersonBean")//注意,因为PsersonBean是 data class 类型 不需要重新toString 函数
        }
    }

    fun onClick(view: View) {
        when (view.id) {
            R.id.btn_refresh -> refreshByrunBlocking2()
            R.id.btn_detail -> detail()
        }
    }

    /**
     * 出现了ANR问题
     */
    fun refreshByrunBlocking() {

        runBlocking(context = Dispatchers.IO) {
            LogUtil.i("开始执行 刷新 耗时操作了")
            delay(30000)//假设30秒,可以假设真实网络请求出现超时了,方便演示出现ANR问题
            psersonBean = PsersonBean("测试用户02")
            LogUtil.i("刷新 耗时操作结束")
        }

        LogUtil.i("刷新 耗时操作 事件执行完毕")
        showData()

    }

    /**
     * runBlocking里即使使用 async 也会出现ANR问题
     */
    fun refreshByrunBlocking2() {

        runBlocking(context = Dispatchers.IO) {
            LogUtil.i("开始执行 刷新 耗时操作了")
            val psersonBean = async {
                delay(30000)//假设30秒,可以假设真实网络请求出现超时了,方便演示出现ANR问题
                PsersonBean("测试用户02")
            }
            LogUtil.i("刷新 耗时操作结束")
        }
        LogUtil.i("刷新 耗时操作 事件执行完毕")
        showData()
    }

    /**
     * 使用GlobalScope.launch ,没有出现ANR问题
     */
    fun refreshByGlobalScopeLaunch() {
        GlobalScope.launch(context = Dispatchers.IO) {
            LogUtil.i("开始执行 刷新 耗时操作了")
            delay(30000)//假设30秒,可以假设真实网络请求出现超时了,方便演示出现ANR问题
            psersonBean = PsersonBean("测试用户02")
            LogUtil.i("刷新 耗时操作结束")
            withContext(Dispatchers.Main){//切换到主线程更新UI
                showData()
            }
        }
        LogUtil.i("调用了 refreshByGlobalScopeLaunch 方法,没有阻塞当前线程")
    }

    fun detail() {
        LogUtil.i("执行了查看详情事件")
        psersonBean.moblie = "12345678901"
        showData()
    }
}

使用GlobalScope.launch解决ANR问题

点击页面上的 刷新按钮 调用 refreshByGlobalScopeLaunch方法,此方法里模拟了等待30秒耗时操作,当点击 刷新按钮 等待3秒左右,点击 详情按钮 ,页面数据正常显示如下图所示

刷新耗时操作结束,主线程更新UI

总结

  1. runBlocking主线程会一直 阻塞 直到 runBlocking 内部的协程执行完毕,执行长时间耗时操作会导致App应用出现ANR问题。
  2. runBlocking里即使使用 async 也会导致App应用出现ANR问题。
  3. GlobalScope.launch可以解决 耗时操作App应用出现ANR问题,注意需要配合withContext(Dispatchers.Main)进行更新UI操作

推荐

Kotlin:协程基础

相关推荐
三少爷的鞋3 分钟前
Main-safe、非阻塞与结构化并发,才是协程架构的核心
android
Brain 博览记20 分钟前
脑机接口研究丨FPGA 5 毫秒完成运动想象分类
开发语言·论文阅读·人工智能·机器学习·fpga开发·分类·数据挖掘
Brain 博览记2 小时前
脑网络AI丨给图神经网络装上“信息高速路”
开发语言·网络·论文阅读·人工智能·深度学习·神经网络·机器学习
郝学胜-神的一滴2 小时前
Effective Python 条款44:善用属性注解
开发语言·c++·vscode·python·算法·stl
Escalating_xu11 小时前
【MySQL】事务管理(上):从 ACID 到提交回滚,把一次转账真正做完整
android·数据库·mysql
两点王爷14 小时前
Java 面试高频:JWT、Cookie、Session、Token 鉴权详解
java·开发语言·面试
微笑星河q16 小时前
C++高阶之【多态】
开发语言·c++
StarsGreen17 小时前
dumpsys gfxinfo数据信息分析方法
android
好的佩奇18 小时前
蓝牙之 GATT 数据模型
android·flutter·蓝牙