简体   繁体   中英

Is UncaughtExceptionHandler set application wide?

I have set an UncaughtExceptionHandler , so that I can write out stack traces to disk when my app crashes. I set this handler like this:

if (!(Thread.getDefaultUncaughtExceptionHandler() instanceof CustomExceptionHandler)) {
         exceptionHandler = new CustomExceptionHandler(
                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString(),
                null, this);

     Thread.setDefaultUncaughtExceptionHandler(exceptionHandler);
}

where CustomExceptionHandler implements UncaughtExceptionHandler . I keep the instance in my Activity , so I can use it for some other functionality (deleting the stack traces, retrieving them, etc).

I call the above piece of code in the onCreate of my Activity , but it seems to only trigger the first time any Activity is run.

I see the Thread.setDefaultUncaughtExceptionHandler call is static though, does that mean I can only set that handler only once in my app? Or can I set it per thread?

From docs

 * Sets the default uncaught exception handler. This handler is invoked in
 * case any Thread dies due to an unhandled exception.

Yep, this handler is global and you need to set it once per app

Is UncaughtExceptionHandler set application wide?

Yes. If you set it in an activity and the activity is destroyed the handler code in the activity may not exist any more.

I have set the handler in the Application-onCreate (not in the Activity) so it works for all Activities that belong to the Application to write crash logs.

For details see How to change crash message in android(if possible)

Here is the gpl-v3+ code for my crashlogger that writes logcat entries to file.

It is initialized in Application.onCreate like this

public class AndroFotoFinderApp extends Application {
    private LogCat mCrashSaveToFile = null;

    @Override public void onCreate() {
        super.onCreate();

        mCrashSaveToFile = new LogCat(this, Global.LOG_CONTEXT, HugeImageLoader.LOG_TAG,
                PhotoViewAttacher.LOG_TAG, CupcakeGestureDetector.LOG_TAG,
                FotoLibGlobal.LOG_TAG, ThumbNailUtils.LOG_TAG, IMapView.LOGTAG,
                ExifInterface.LOG_TAG, ImageMetaReader.LOG_TAG);
    }
}

where the constants Global.LOG_CONTEXT , HugeImageLoader.LOG_TAG , ... are android logging tags of different moduls of my code use like this

Log.d(HugeImageLoader.LOG_TAG, "some log message from modul HugeImageLoader)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM