Android exception handling best practice?

后端 未结 3 1799
生来不讨喜
生来不讨喜 2020-11-29 16:26

If my app crashes, it hangs for a couple of seconds before I\'m told by Android that the app crashed and needs to close. So I was thinking of catching all exceptions in my a

3条回答
  •  既然无缘
    2020-11-29 16:49

    Here, check for the link for reference.

    In here you create a class say ExceptionHandler that implements java.lang.Thread.UncaughtExceptionHandler..

    Inside this class you will do your life saving stuff like creating stacktrace and gettin ready to upload error report etc....

    Now comes the important part i.e. How to catch that exception. Though it is very simple. Copy following line of code in your each Activity just after the call of super method in your overriden onCreate method.

    Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));
    

    Your Activity may look something like this…

    public class ForceClose extends Activity {
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));
    
            setContentView(R.layout.main);
        }
    }
    

    Hope this helps...

提交回复
热议问题