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:
I have an app, which is using some 3rd party library (ad network provider SDK - specifically - AdMob
SDK, based on Google Play Services
). Functionality of this library is not critical for the application. The library creates one or more background worker threads. Sometimes (very rare case) there is an unhandled exception in one of these background threads, causing to crashing the application. I'd like to ignore all exceptions, caused by this library, regardless of their cause: in worst case the app user will not see an ad - it's much better than app crash.
Since the library itself creates the background threads - I cannot just wrap them by try/catch.
Question
Is there any way to catch all non-handled background (non-main) thread exceptions and just to kill the thread in such case, and to prevent app crash?
Related questions
I saw a lot of several questions, but some of them are too specific (and not covering my case), others refer to situation when the developer has a control on thread creation and is able to wrap the whole thread with try/catch. If I still missed the relevant question, covering this case, I will appreciate the link
As mentioned above, Thread.setDefaultUncaughtExceptionHandler is the proper way to handle this. Create the class:
Then call setDefaultUncaughtExceptionHandler from your main thread:
All you need to do is Extend all the activities with BaseActivity. The app never crashes at any point
Code sniplet for BaseActivity :