解決android 異常致使應用程序中止運行的錯誤

(一) 前言
各位親愛的午餐童鞋,是否是常常由於本身的程序中出現未層捕獲的異常致使程序異常終止而痛苦不已?嗯,是的。。 可是,你們不要怕,今天給你們分享一個東東能夠解決你們這種困擾,吼吼!

(二) UncaughtExceptionHandler接口
這個接口,顧名思義,就是處理程序中沒有處理的異常,並且是在系統拋出異常致使程序異常終止以前哦!那麼,在Android裏面怎麼使用呢?

(三) 怎麼使用UncaughtExceptionHandler
1. 首先,我們得建立一個UncaughtExceptionHandler的具體類,好比:php

複製內容到剪貼板
代碼:
public class CrashHandler implements UncaughtExceptionHandler {

   private static CrashHandler instance;  //單例引用,這裏咱們作成單例的,由於咱們一個應用程序裏面只須要一個UncaughtExceptionHandler實例

   private CrashHandler(){}

   public synchronized static CrashHandler getInstance(){  //同步方法,以避免單例多線程環境下出現異常
       if (instance == null){
           instance = new CrashHandler();
       }
       return instance;
   }

   public void init(Context ctx){  //初始化,把當前對象設置成UncaughtExceptionHandler處理器
       Thread.setDefaultUncaughtExceptionHandler(this);
   }

@Override
   public void uncaughtException(Thread thread, Throwable ex) {  //當有未處理的異常發生時,就會來到這裏。。
       Log.d("Sandy", "uncaughtException, thread: " + thread
               + " name: " + thread.getName() + " id: " + thread.getId() + "exception: "
               + ex);
            String threadName = thread.getName();
            if ("sub1".equals(threadName)){
                  Log.d("Sandy", ""xxx);
            }else if(){
                     //這裏咱們能夠根據thread name來進行區別對待,同時,咱們還能夠把異常信息寫入文件,以供後來分析。
             }
   }

}
2. 其次,咱們自定義Application類
複製內容到剪貼板
代碼:
public class OurApplication extends Application {

@Override
   public void onCreate() {
       super.onCreate();
       CrashHandler handler = CrashHandler.getInstance();
       handler.init(getApplicationContext()); //在Appliction裏面設置咱們的異常處理器爲UncaughtExceptionHandler處理器
   }
}
3. 配置AndroidManifest.xml文件
因爲咱們使用自定義的Application,因此咱們要在AndroidManifest.xml文件中申明它
複製內容到剪貼板
代碼:
<application
       android:icon="@drawable/ic_launcher"
       android:label="@string/app_name"
       android:name=".OurApplication"
       android:debuggable="true"
       >
4. 測試
咱們在Activity裏面啓動一個線程,而後線程裏面拋出一個異常,看看程序會怎麼樣
複製內容到剪貼板
代碼:
Button btn = (Button) findViewById(R.id.bt);
       btn.setOnClickListener(new View.OnClickListener() {
@Override
           public void onClick(View v) {

               Thread thread = new Thread(new Runnable() {
@Override
                   public void run() {
                       Log.d("Sandy", "I am a sub thread");
                       String s = null;
                       s.toString();  //拋出NullPointException
                   }
               }, "sub  thread");
               thread.start();
5. 結果
因爲咱們有默認未處理異常的處理程序,因此會打印下面的日誌信息,而不會拋出異常致使程序異常終止
D/Sandy   ( 2228): I am a sub thread

D/Sandy   ( 2228): uncaughtException, thread: Thread[sub  thread,5,main] name: sub  thread id: 148exception: java.lang.NullPointerExceptionhtml

轉載:http://bbs.51cto.com/thread-1037088-1.htmljava

相關文章
相關標籤/搜索