How to prevent android app from crashing due to ex

2019-01-21 23:55发布

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

2条回答
2楼-- · 2019-01-22 00:47

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());
查看更多
成全新的幸福
3楼-- · 2019-01-22 00:48

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());
            }
        });
    }
}
查看更多
登录 后发表回答