JavaCrashCatcher.kt 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package com.dolin.zap.crashlytics
  2. import android.os.Process
  3. import com.dolin.zap.Zap
  4. import kotlin.system.exitProcess
  5. /**
  6. * @author #Suyghur.
  7. * Created on 4/12/21
  8. */
  9. class JavaCrashCatcher : Thread.UncaughtExceptionHandler {
  10. private val defaultHandler = Thread.getDefaultUncaughtExceptionHandler()
  11. private var intercept = false
  12. fun initialize() {
  13. try {
  14. Thread.setDefaultUncaughtExceptionHandler(this)
  15. } catch (e: Exception) {
  16. Zap.e("JavaCrashCatcher->setDefaultUncaughtExceptionHandler() error , ${e.localizedMessage}")
  17. }
  18. }
  19. override fun uncaughtException(t: Thread, e: Throwable) {
  20. if (defaultHandler != null) {
  21. Thread.setDefaultUncaughtExceptionHandler(defaultHandler)
  22. }
  23. try {
  24. handleException(t, e)
  25. } catch (e: Exception) {
  26. Zap.e("JavaCrashCatcher->handlerException error , ${e.localizedMessage}")
  27. }
  28. if (intercept) {
  29. Process.killProcess(Process.myPid())
  30. exitProcess(10)
  31. } else {
  32. defaultHandler?.apply {
  33. uncaughtException(t, e)
  34. }
  35. }
  36. }
  37. private fun handleException(t: Thread, e: Throwable) {
  38. }
  39. companion object {
  40. fun getInstance(): JavaCrashCatcher {
  41. return JavaCrashCatcherHolder.INSTANCE
  42. }
  43. private object JavaCrashCatcherHolder {
  44. val INSTANCE = JavaCrashCatcher()
  45. }
  46. /**
  47. * 防止单例对象在反序列化时重新生成对象
  48. */
  49. private fun readResolve(): Any {
  50. return JavaCrashCatcherHolder.INSTANCE
  51. }
  52. }
  53. }