如何在App崩溃时执行一段代码

其实这个算是java的知识,在程序抛出无法捕捉的异常时,会触发Thread中的defaultUncaughtExceptionHandleruncaughtException方法,UncaughtExceptionHandler就是下面这个接口

public interface UncaughtExceptionHandler {
        /**
         * Method invoked when the given thread terminates due to the
         * given uncaught exception.
         * <p>Any exception thrown by this method will be ignored by the
         * Java Virtual Machine.
         * @param t the thread
         * @param e the exception
         */
        void uncaughtException(Thread t, Throwable e);
    }

当然Android中系统自己实现了这个接口,就是下面的KillApplicationHandler

/**
     * Handle application death from an uncaught exception.  The framework
     * catches these for the main threads, so this should only matter for
     * threads created by applications.  Before this method runs,
     * {@link LoggingHandler} will already have logged details.
     */
    private static class KillApplicationHandler implements Thread.UncaughtExceptionHandler {
        public void uncaughtException(Thread t, Throwable e) {
            try {
                // Don't re-enter -- avoid infinite loops if crash-reporting crashes.
                if (mCrashing) return;
                mCrashing = true;

                // Try to end profiling. If a profiler is running at this point, and we kill the
                // process (below), the in-memory buffer will be lost. So try to stop, which will
                // flush the buffer. (This makes method trace profiling useful to debug crashes.)
                if (ActivityThread.currentActivityThread() != null) {
                    ActivityThread.currentActivityThread().stopProfiling();
                }

                // Bring up crash dialog, wait for it to be dismissed
                ActivityManager.getService().handleApplicationCrash(
                        mApplicationObject, new ApplicationErrorReport.ParcelableCrashInfo(e));
            } catch (Throwable t2) {
                if (t2 instanceof DeadObjectException) {
                    // System process is dead; ignore
                } else {
                    try {
                        Clog_e(TAG, "Error reporting crash", t2);
                    } catch (Throwable t3) {
                        // Even Clog_e() fails!  Oh well.
                    }
                }
            } finally {
                // Try everything to make sure this process goes away.
                Process.killProcess(Process.myPid());
                System.exit(10);
            }
        }
    }

在App启动时,App会执行这个语句

Thread.setDefaultUncaughtExceptionHandler(new KillApplicationHandler());

这样Android就完全接管了不可捕捉的异常,也就是Crash,可以看到,Android的处理到最后是把当前进程给结束了,这就是Crash后App会闪退的原因了。

finally {
                // Try everything to make sure this process goes away.
                Process.killProcess(Process.myPid());
                System.exit(10);
            }

因此我们要自己处理Crash的话也需要自己实现一个UncaughtExceptionHandler,然后在Application类中进行设置

class App : Application() {
    override fun onCreate() {
        super.onCreate()
       Thread.setDefaultUncaughtExceptionHandler(MyUncaughtExceptionHandler());
    }

这样做的好处有很多,比如可以在这里将异常上传至服务器,也可以给用户有好的提示,或者是掩盖错误,直接返回到出错之前的页面。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 176,235评论 25 709
  • 1 什么是Crash Crash,即闪退,多指在移动设备(如iOS、Android设备)中,在打开应用程序时出现的...
    天才木木阅读 57,589评论 37 281
  • 《腾讯桌球:客户端总结》 本次分享总结,起源于腾讯桌球项目,但是不仅仅限于项目本身。虽然基于Unity3D,很多东...
    吴秦阅读 25,048评论 12 142
  • 前言 大家都知道,安装Android系统的手机版本和设备千差万别,在模拟器上运行良好的程序安装到某款手机上说不定就...
    开发者小王阅读 9,327评论 4 4
  • 不要当父母需要你时,除了泪水,一无所有。 不要当孩子需要你时,除了惭愧,一无所有。 不要当自己回首过去,除了蹉跎,...
    懒猫物语阅读 1,477评论 2 2

友情链接更多精彩内容