轉:Android應用崩潰後異常捕獲並重啟

來源:互聯網
上載者:User

標籤:android   blog   http   java   使用   io   strong   ar   

轉自:here

在Android應用開發中,偶爾會因為某些異常導致正在使用的應用出現異常並強制關閉,這樣導致不友好的使用者體驗。為瞭解決這個問題,我們需要捕獲出現的異常並做處理。在Java中有兩類異常,分別是Error和RuntimeException,前者是不需要我們去處理的,我們處理的往往是後者。那麼如何捕獲線程在運行時的異常呢,我們可以使用自訂類實現

Thread.UncaughtExceptionHandler介面並複寫uncaughtException(Thread thread, Throwable ex)方法來實現對運行時線程進行異常處理。在Android中我們可以實現自己的Application類,然後實現UncaughtExceptionHandler介面,並在uncaughtException方法中處理異常,這裡我們關閉App並啟動我們需要的Activity,下面看代碼:

 

[java] view plaincopy 
  1. public class MyApplication extends Application implements  
  2.         Thread.UncaughtExceptionHandler {  
  3.     @Override  
  4.     public void onCreate() {  
  5.         super.onCreate();  
  6.         //設定Thread Exception Handler  
  7.         Thread.setDefaultUncaughtExceptionHandler(this);  
  8.     }  
  9.   
  10.     @Override  
  11.     public void uncaughtException(Thread thread, Throwable ex) {  
  12.         System.out.println("uncaughtException");  
  13.         System.exit(0);  
  14.         Intent intent = new Intent(this, MainActivity.class);  
  15.         intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |  
  16.         Intent.FLAG_ACTIVITY_NEW_TASK);  
  17.         startActivity(intent);  
  18.     }  
  19.       
  20. }  


最後需要在Manifest中配置Application的標籤android:name=".MyApplication",讓整個應用程式使用我們自訂的Application類,這樣就實現了當應用遇到崩潰異常時重啟應用的效果。

 

我們在任意一個Activity中主動拋出下面異常,就會發現應用遇到異常後重啟了,如果不處理的話,應用在遇到異常後就關閉了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.