在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()
}
}
```