android崩潰重啟,android崩潰

來源:互聯網
上載者:User

android崩潰重啟,android崩潰
在Android應用開發中,偶爾會因為某些異常導致正在使用的應用出現異常並強制關閉,這樣導致不友好的使用者體驗。為瞭解決這個問題,我們需要捕獲出現的異常並做處理。在Java中有兩類異常,分別是Error和RuntimeException,前者是不需要我們去處理的,我們處理的往往是後者。那麼如何捕獲線程在運行時的異常呢,我們可以使用自訂類實現
Thread.UncaughtExceptionHandler 介面並複寫uncaughtException(Thread thread, Throwable ex)方法來實現對運行時線程進行異常處理。在Android中我們可以實現自己的Application類,然後實現 UncaughtExceptionHandler介面,並在uncaughtException方法中處理異常,這裡我們關閉App並啟動我們需要的Activity,下面看代碼:



public class MyApplication extends Application implements 
        Thread.UncaughtExceptionHandler { 
    @Override 
    public void onCreate() { 
        super.onCreate(); 
        //設定Thread Exception Handler 
        Thread.setDefaultUncaughtExceptionHandler(this); 
    } 
   
    @Override 
    public void uncaughtException(Thread thread, Throwable ex) { 
        System.out.println("uncaughtException"); 
        System.exit(0); 
        Intent intent = new Intent(this, MainActivity.class); 
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | 
        Intent.FLAG_ACTIVITY_NEW_TASK); 
        startActivity(intent); 
    } 
       
}
最後需要在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.