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

前端 未结 2 966
悲&欢浪女
悲&欢浪女 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:44

    All you need to do is Extend all the activities with BaseActivity. The app never crashes at any point

    Code sniplet for BaseActivity :

    public class BaseActivity extends Activity{
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
                public void uncaughtException(Thread paramThread, Throwable paramThrowable) {
                    Log.e("Error"+Thread.currentThread().getStackTrace()[2],paramThrowable.getLocalizedMessage());
                }
            });
        }
    }
    
    0 讨论(0)
  • 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());
    
    0 讨论(0)
提交回复
热议问题