利用Android UncaughtExceptionHandler捕獲崩潰異常

來源:互聯網
上載者:User

在編寫APK程式時,通常會導致程式崩潰的異常,在通常情況下這些異常不能被捕獲到,利用Thread.UncaughtExceptionHandler就可以捕獲到這些異常。從名字就可以看出來UncaughtExceptionHandler是針對某個線程而言的,同時Thread提供了3個相關的方法:

   1. void setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler eh)  //
為一個線程設定一個Handler
   2. Thread.UncaughtExceptionHandler getUncaughtExceptionHandler()         //擷取該線程的handler
      
   3. static void setDefaultUncaughtExceptionHandler(Thread.UncaughtExceptionHandler eh)

      //為一個線程設定一個預設的Handler,在程式不能捕獲而退出,並且麼有其他的handler時被調用!

       所以只要通過set方法,為一個線程設定一個handler就可以在程式異常退出時,捕獲改異常,Demo1:

       Thread thread = new thread(new Runnable(){
            public void run() {
                //Do something can throw runtime exception.
            }
        });
       thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler(){
           @Override
           public void uncaughtException(Thread thread, Throwable ex) {
           //TODO
               System.out.println(ex.getLocalizedMessage());
            });

               線程的運行時異常就會被捕獲,你就可以對捕獲到異常進行處理

但是,由於在android編程中,大量使用線程,如果統一處理呢?因為主線程只有一個,我們可以在主線程裡處理。
我們可以在主activity啟動時的oncreate方法裡面添加下面代碼

Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
public void uncaughtException(Thread thread, Throwable ex) {
//TODO 當程式發生不能被捕獲的異常時,就會被調用,可以在這裡進行釋放資源,中斷連線並進行友好提示的操作等!

System.out.println(ex.getLocalizedMessage());

finish();
}
});

這樣就可以捕獲大部分的運行時異常了

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.