在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()
}
}
```
本文详细描述了如何在Android应用中创建MyApplication类,并在AndroidManifest.xml中进行注册。特别关注attachBaseContext方法,其中展示了如何使用Handler和Looper处理主线程和子线程的异常。
1250

被折叠的 条评论
为什么被折叠?



