Android应用的场景如下
MainActivity
- FooActivity1
- FooActivity2
应用程序以MainActivity启动,可以启动FooActivity1和FooActivity2。
我正在尝试检测 FooActivity1 中的崩溃。是的,我确实知道 UncaughtExceptionHandler 并用它来捕获崩溃,但我怀疑它错过了很多。这是我正在使用的逻辑:
在 FooActivity1 中:
@Override
protected void onStart() {
super.onStart();
//set a flag called NormalFooActivity1Exit to false in shared preferences
...
}
@Override
protected void onStop() {
super.onStop();
//set the flag called NormalFooActivity1Exit to true in shareed preferences
...
}
在主活动中
@Override
public void onCreate(Bundle savedInstanceState) {
//Check the flag.
//If it is true, do nothing
//If it is false, record a crash and set the flag to true.
}
本质是,如果在应用程序下次启动之前跳过 onStop(),则假定发生崩溃。报告的数据给我的印象是,这样的崩溃率被高估了。
有人能指出这个逻辑的缺陷吗?
您可以简单地在应用程序中设置崩溃检测而不是活动。因为崩溃可能随时随地发生,你不能只为每种可能性设置标志,除非它是一个非常小的应用程序。
这是获取应用程序中发生的所有崩溃的一种方法
class YourApp : Application(), ExceptionListener {
override fun onCreate() {
super.onCreate()
setupExceptionHandler()
//... other code
}
override fun uncaughtException(thread: Thread, throwable: Throwable) {
// TODO: Here Make sure you are logging this issue some where like Crashlytics or in whatever counter you have in preferences.
// Also indicate that something went wrong to the user like maybe a dialog or an activity.
Toast.makeText(
this,
"An Uncaught Exception occured : ${throwable.message}",
Toast.LENGTH_LONG
).show()
log(throwable)
}
private fun setupExceptionHandler() {
Handler(Looper.getMainLooper()).post {
while (true) {
try {
Looper.loop()
} catch (e: Throwable) {
uncaughtException(Looper.getMainLooper().thread, e)
}
}
}
Thread.setDefaultUncaughtExceptionHandler { t, e ->
uncaughtException(t, e)
}
}
}
interface ExceptionListener {
fun uncaughtException(thread: Thread, throwable: Throwable)
}
这是一种更通用的方法,也可能不适合需要崩溃才能关闭应用程序的应用程序,因为此代码将阻止应用程序在崩溃时关闭。所以明智地使用它。