Android app异常,继续执行任务

本文详细描述了如何在Android应用中创建MyApplication类,并在AndroidManifest.xml中进行注册。特别关注attachBaseContext方法,其中展示了如何使用Handler和Looper处理主线程和子线程的异常。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在app模块下,新建MyApplication,在AndroidManifest.xml中注册

AndroidManifest.xml中注册:

<application
        android:name=".MyApplication"
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:networkSecurityConfig="@xml/network_security_config"
        android:requestLegacyExternalStorage="true"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.Robot"
        tools:targetApi="31">

MyApplication中的代码如下:

override fun attachBaseContext(base: Context?) {
        super.attachBaseContext(base)
        val handler = Handler(mainLooper)
        handler.post(Runnable {
            while (true) {
                try {
                    //try-catch主线程的所有异常;Looper.loop()内部是一个死循环,出现异常时才会退出,所以这里使用while(true)。
                    Looper.loop()
                } catch (e: Throwable) {
                    e.printStackTrace()
                }
            }
        })
        Thread.setDefaultUncaughtExceptionHandler { thread, e -> //try-catch子线程的所有异常。
            e.printStackTrace()
        }
    }
    ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值