Need to handle uncaught exception and send log file

后端 未结 7 870
时光说笑
时光说笑 2020-11-22 15:42

UPDATE: Please see \"accepted\" solution below

When my app creates an unhandled exception, rather than simply terminating, I\'d like to first give t

7条回答
  •  渐次进展
    2020-11-22 16:10

    @PeriHartman's answer works well when the UI thread throws uncaught exception. I made some improvements for when the uncaught exception is thrown by a non UI thread.

    public boolean isUIThread(){
        return Looper.getMainLooper().getThread() == Thread.currentThread();
    }
    
    public void handleUncaughtException(Thread thread, Throwable e) {
        e.printStackTrace(); // not all Android versions will print the stack trace automatically
    
        if(isUIThread()) {
            invokeLogActivity();
        }else{  //handle non UI thread throw uncaught exception
    
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    invokeLogActivity();
                }
            });
        }
    }
    
    private void invokeLogActivity(){
        Intent intent = new Intent ();
        intent.setAction ("com.mydomain.SEND_LOG"); // see step 5.
        intent.setFlags (Intent.FLAG_ACTIVITY_NEW_TASK); // required when starting from Application
        startActivity (intent);
    
        System.exit(1); // kill off the crashed app
    }
    

提交回复
热议问题