Can I call a method before my application go to crash

前端 未结 5 1272
庸人自扰
庸人自扰 2020-12-30 16:26

I\'m a newbie in android and I always see Exception when I\'m running my code. So, somebody can tell me Can I call a method before app go to crash anywhere without \"try-cat

5条回答
  •  失恋的感觉
    2020-12-30 17:06

    Try this way

    1) create class

    import android.content.Context;
    import android.content.Intent;
    import android.os.Process;
    
    import java.io.PrintWriter;
    import java.io.StringWriter;
    import java.lang.Thread.UncaughtExceptionHandler;
    
    public class CrashReportHandler implements UncaughtExceptionHandler {
    
        public static void attach(Context context) {
            Thread.setDefaultUncaughtExceptionHandler(
                    new CrashReportHandler(context)
            );
        }
    
        ///////////////////////////////////////////// implementation
    
        private CrashReportHandler(Context context) {
            m_context = context;
        }
    
        public void uncaughtException(Thread thread, Throwable exception) {
            StringWriter stackTrace = new StringWriter();
            exception.printStackTrace(new PrintWriter(stackTrace));
    
            //You will get call back here when app crashes.
    
            // from RuntimeInit.crash()
            Process.killProcess(Process.myPid());
            System.exit(10);
        }
    
        private Context m_context;
    
    }
    

    How to use this class?

    write this line in your activity onCreate() method

    CrashReportHandler.attach(this);
    

提交回复
热议问题