2017-08-28 68 views
0

我已經設置了一個UncaughtExceptionHandler,以便我的應用程序崩潰時可以將堆棧跟蹤寫入磁盤。我設置的處理程序是這樣的:UncaughtExceptionHandler是否設置了應用程序範圍?

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

    Thread.setDefaultUncaughtExceptionHandler(exceptionHandler); 
} 

其中CustomExceptionHandler實現UncaughtExceptionHandler。我將實例保存在我的Activity中,因此我可以將它用於其他一些功能(刪除堆棧跟蹤,檢索它們等)。

我在我的ActivityonCreate中調用了上面的那段代碼,但它似乎只在第一次運行任何Activity時觸發。

我看到Thread.setDefaultUncaughtExceptionHandler調用是靜態的,這是否意味着我只能在應用程序中設置該處理程序一次?或者我可以每個線程設置它?

回答

0

從文檔

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

沒錯,這個處理器是全球性,你需要爲每個應用程序

0

是UncaughtExceptionHandler的設置應用廣泛,一旦設置呢?

是的。如果將其設置爲活動並且活動已被銷燬,則活動中的處理程序代碼可能不再存在。

我已經在Application-onCreate(不在Activity)中設置處理程序,因此它適用於屬於應用程序寫入崩潰日誌的所有活動。

詳見How to change crash message in android(if possible)

Here是遵循GPL V3 +代碼爲我crashlogger寫入logcat的條目文件。

它在Application.onCreate這樣

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); 
    } 
} 

其中常數Global.LOG_CONTEXTHugeImageLoader.LOG_TAG ... 是我的代碼中使用的不同moduls Android的日誌記錄標籤這樣

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