How to prevent android app from crashing due to exception in background thread?

前端 未结 2 978
悲&欢浪女
悲&欢浪女 2020-12-13 10:50

It\'s a general question, which raised from specific scenario, but I\'d like to get a general answer how to deal with the following situation:

Background:

2条回答
  •  臣服心动
    2020-12-13 11:49

    As mentioned above, Thread.setDefaultUncaughtExceptionHandler is the proper way to handle this. Create the class:

     private class MyThreadUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
    
        @Override
        public void uncaughtException(Thread thread, Throwable ex) {
            Log.e(TAG, "Received exception '" + ex.getMessage() + "' from thread " + thread.getName(), ex);
        }
    }
    

    Then call setDefaultUncaughtExceptionHandler from your main thread:

     Thread t = Thread.currentThread();
     t.setDefaultUncaughtExceptionHandler(new MyThreadUncaughtExceptionHandler());
    

提交回复
热议问题