Код: Выделить всё
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
LOG("MainActivity.onCreate(Bundle?)")
super.onCreate(savedInstanceState)
// Register the 'catch-all' exception handler
Thread.setDefaultUncaughtExceptionHandler(CustomUncaughtExceptionHandler())
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
// Example of a call to a native method
binding.sampleText.text = stringFromJNI()
testExceptionHandler()
LOG("Returning from Activity.onCreate()")
}
}
Код: Выделить всё
private fun testExceptionHandler() {
LOG("testExceptionHandler()")
LOG("Raising exception...")
throw NullPointerException()
}
Код: Выделить всё
class CustomUncaughtExceptionHandler: Thread.UncaughtExceptionHandler {
override fun uncaughtException(p0: Thread, p1: Throwable) {
LOG("uncaughtException(Thread, Throwable)")
var exceptionType: String = "(null)"
when (p1) {
is IndexOutOfBoundsException -> {
exceptionType = "IndexOutOFBoundsException"
}
is NullPointerException -> {
exceptionType = "NullPointerException"
}
is ArithmeticException -> {
exceptionType = "ArithmeticException"
}
is RuntimeException -> {
exceptionType = "RuntimeException"
}
else -> {
exceptionType = "Unknown"
}
}
LOG("Exception type = $exceptionType")
LOG("Already in main thread... Preparing to display alert...")
displayAlert(exceptionType)
LOG("Returning from default uncaught exception handler...")
}
private fun displayAlert(exceptionType: String) {
LOG("Displaying error on foreground activity...")
val builder : AlertDialog.Builder = AlertDialog.Builder(ContextMgr.activityCtx!!)
builder.setTitle("Something went wrong!!")
builder.setMessage(exceptionType)
builder.setCancelable(false)
builder.setPositiveButton("Restart") { _, _ ->
LOG("Restart the app...")
}
val alertdialog : AlertDialog = builder.create()
alertdialog.show()
}
}
Проблема в том, что пользовательский интерфейс застрял вот так:

Нормальный сток без каких-либо бросков исключение привело бы к минимальному пользовательскому интерфейсу с текстом «Привет из C++». Это пользовательский интерфейс собственного шаблона проекта Android.
Просматривая журналы,
Код: Выделить всё
MainActivity.onCreate(Bundle?)
testExceptionHandler()
Raising exception...
....
// stack trace
....
uncaughtException(Thread, Throwable)
Exception type = RuntimeException
Already in main thread... Preparing to display alert...
Returning from default uncaught exception handler...
Журналы также показывают, что поток никогда не возвращался из onCreate, а onResume, onStart никогда не вызывался.
Итак, мой AlertDialog не удалось, потому что произошло исключение, действие не завершило свой жизненный цикл и поэтому не может ничего показать пользователю? Если это правда, как я могу это исправить? Если возможно, я бы хотел показать свой AlertDialog или, по крайней мере, процесс должен завершиться вместо того, чтобы показывать... какой бы ни был этот пользовательский интерфейс.
Update1 - My среда:
Ссылка на мой проект — [AndroidExceptionHandling][3]
Подробности AS: Android Studio Iguana | 2023.2.1 Патч 2
Подробности эмулятора:
- AvdId: Tiramisu_Pixel_8_Pro_API_33_
- образ. androidVersion.api: 33
- image.sysdir.1: system-images\android-33\google_apis_playstore\x86_64\
Подробнее здесь: https://stackoverflow.com/questions/791 ... ain-thread