android 自定義全局未處理異常捕獲器
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">
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!