Код: Выделить всё
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< /code> не удалось, потому что произошло исключение, действие не завершило свой жизненный цикл и поэтому не может ничего показать пользователю? Если это правда, как я могу это исправить? Если возможно, я бы хотел показать свой AlertDialog, или, по крайней мере, процесс должен завершиться, а не показывать... какой бы ни был этот пользовательский интерфейс.
Подробнее здесь: https://stackoverflow.com/questions/791 ... ain-thread