android 異常捕獲-UncaughtExceptionHandler

Android 編程過程當中發生了沒有被 catch 的異常後會怎麼辦,毫無疑問,應用會被強制關閉。java

因此,通常爲了保險起見,咱們能夠在 Application#onCreate 方法中,爲線程設置默認的異常處理器。即:UncaughtExceptionHandler編程

因而,捕獲異常的代碼能夠這麼寫:ide

Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread t, Throwable e) {
                Log.i(TAG, "uncaughtException: " + t.getName() + ", e :" + e.getMessage());
                ///能夠將異常進一步處理
            }
        });
複製代碼

然而,這樣處理還不夠!ui

當發生異常的是非UI線程時,這樣處理是可行的。可是當發生異常的是UI線程時,那麼這樣處理,在用戶的眼中,就是Activity卡死,且沒法響應操做。this

那麼怎麼在 UI Thread Crash以後重啓Activity呢,能夠爲 UI Thread 添加一個本身 UncaughtExceptionHandlerspa

Thread.currentThread().setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread t, Throwable e) {
                Log.i(TAG, "ui exception: " + t.getName() + ", e :" + e.getMessage());
                Intent intent = new Intent(AppContext.this, MainActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);

                Process.killProcess(Process.myPid());
                System.exit(0);
            }
        });
複製代碼

這樣就能夠在UI應用發生未捕獲異常以後,重啓應用到主頁面了。線程

相關文章
相關標籤/搜索