android 自定义全局未处理异常捕获器

jopen 10年前

1:异常处理捕获类

package com.oa.main.common.tool;    import android.content.Context;  import android.util.Log;    /**   * 自定义全局未处理异常捕获器   * Created  on 13-12-13.   */  public class CrashHandler implements Thread.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);      }        public void uncaughtException(Thread thread, Throwable ex) {  //当有未处理的异常发生时,就会来到这里。。          Log.d("----------------捕获异常-------------!", "uncaughtException, thread: " + thread                  + " name: " + thread.getName() + " id: " + thread.getId() + "exception: "                  + ex);          String threadName = thread.getName();          //这里我们可以根据thread name来进行区别对待,同时,我们还可以把异常信息写入文件,以供后来分析。  //        if ("sub1".equals(threadName)) {  //        } else if () {  //        }      }      }



二:设置全局Application

public class ApplicationTrans extends Application {        @Override      public void onCreate() {          super.onCreate();          CrashHandler handler = CrashHandler.getInstance();          handler.init(getApplicationContext()); //在Appliction里面设置我们的异常处理器为UncaughtExceptionHandler处理器      }  }



三:在androidManifest中配置全局

<application          android:allowBackup="true"          android:icon="@drawable/ic_launcher"          android:label="@string/app_name"          android:theme="@style/activityTheme"          android:name=".common.entity.ApplicationTrans"          android:debuggable="true">



到此自定义捕获未处理异常结束!