標籤:android style class blog code java
(一) 前言
各位親愛的午飯童鞋,是不是經常因為自己的程式中出現未層捕獲的異常導致程式異常終止而痛苦不已?嗯,是的。。 但是,大家不要怕,今天給大家分享一個東東可以解決大家這種困擾,吼吼!
(二) UncaughtExceptionHandler介面
這個介面,顧名思義,就是處理常式中沒有處理的異常,而且是在系統拋出異常導致程式異常終止之前哦!那麼,在Android裡面怎麼使用呢?
(三) 怎麼使用UncaughtExceptionHandler
1. 首先,咱們得建立一個UncaughtExceptionHandler的具體類,比如:
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.NullPointerException
大家還等什麼呢?趕緊在自己的應用裡面添加上預設未處理異常處理器吧!再也不會因為異常未捕獲發生程式崩潰了。。^_^