CustomCrashHandler.ets 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import { hiAppEvent } from '@kit.PerformanceAnalysisKit';
  2. import { router } from '@kit.ArkUI';
  3. /**
  4. * 自定义崩溃处理工具类
  5. * 替代 spider-man 的默认崩溃页面,使用我们自定义的崩溃页面
  6. */
  7. export class CustomCrashHandler {
  8. /**
  9. * 初始化自定义崩溃处理,替代 spider-man 的默认行为
  10. */
  11. static init() {
  12. // 添加自己的崩溃监听器
  13. hiAppEvent.addWatcher({
  14. name: 'CustomSpiderMan',
  15. appEventFilters: [{
  16. domain: hiAppEvent.domain.OS,
  17. names: [hiAppEvent.event.APP_CRASH]
  18. }],
  19. onReceive: (domain: string, appEventGroups: Array<hiAppEvent.AppEventGroup>) => {
  20. console.error('CustomCrashHandler onReceive -- ' + domain);
  21. if (appEventGroups.length < 1) {
  22. console.error('appEventGroups.length < 1');
  23. return;
  24. }
  25. // 取第一个崩溃事件组
  26. const appEventGroup = appEventGroups[0];
  27. CustomCrashHandler.openCustomCrashPage(appEventGroup);
  28. },
  29. });
  30. }
  31. /**
  32. * 打开自定义崩溃页面
  33. */
  34. static openCustomCrashPage(appEventGroup: hiAppEvent.AppEventGroup) {
  35. setTimeout(() => {
  36. router.pushNamedRoute({
  37. name: 'CustomCrashPage',
  38. params: appEventGroup
  39. }).then(() => {
  40. console.error('CustomCrashPage pushNamedRoute success');
  41. }).catch(() => {
  42. console.error('CustomCrashPage pushNamedRoute failed');
  43. // 如果命名路由失败,尝试使用普通路由
  44. router.pushUrl({
  45. url: 'pages/CustomCrashPage',
  46. params: appEventGroup
  47. }).catch(() => {
  48. console.error('CustomCrashPage pushUrl also failed');
  49. });
  50. });
  51. }, 1000);
  52. }
  53. }