Android 全局异常捕获

全局异常捕获

废话不多说,直接上代码

package com.util;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.Thread.UncaughtExceptionHandler;

import android.content.Context;

/**
 *  全局异常捕获句柄类
 */
public class CrashHandler implements UncaughtExceptionHandler {

    public static final String TAG = "CrashHandler";
    public static final boolean DEBUG = false; // 是否开启日志输出,在Debug状态下开启,
                                                // 在Release状态下关闭以提高程序性能

    private static CrashHandler crashHandler;

    private Thread.UncaughtExceptionHandler exceptionHandler; // 系统默认的UncaughtExceptionHandler
    private Context context;

    /**
     * 私有构造函数
     */
    private CrashHandler() {
    }

    /**
     * @return 单例
     */
    public static CrashHandler getInstance() {
        if (crashHandler == null) {
            crashHandler = new CrashHandler();
        }
        return crashHandler;
    }

    /**
     * @param context
     *            上下文对象
     */
    public void init(Context context) {
        this.context = context;
        exceptionHandler = Thread.getDefaultUncaughtExceptionHandler(); // 获取系统默认的UncaughtExceptionHandler
        Thread.setDefaultUncaughtExceptionHandler(this); // 设置本类对象crashHandler为程序的默认处理器
    }

    /**
     * 当异常发生时,捕获异常
     * 
     * @param thread
     *            线程
     * @param ex
     *            异常
     */
    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        if (!handleException(thread, ex) && exceptionHandler != null) {
            exceptionHandler.uncaughtException(thread, ex); // 如果用户没有处理则让系统默认的异常处理器来处理
        } else {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                SLog.Console("===============CrashHandler================");
                SLog.saveException(e);
                SLog.Console("==============CrashHandlerEnd==============");
            }
        }
    }

    /**
     * 自定义异常处理
     * 
     * @param ex
     *            异常
     * @return boolean 是否处理
     */
    private boolean handleException(Thread thread,  Throwable ex) {
        if (ex == null) {
            return true;
        }
         StringWriter sw = new StringWriter();  
            PrintWriter pw = new PrintWriter(sw, true);  
            ex.printStackTrace(pw);  
            pw.flush();  
            sw.flush();  
        this.saveInfo2File(ex); // 保存错误报告文件
        return true;
    }

    /**
     * 保存异常信息到文件中
     * 
     * @param ex
     *            异常
     * @return String 异常信息
     */
    public String saveInfo2File(final Throwable ex) {
//      if (MainApplication.getInstance().isTest) {
//          new Thread(){    
//              @Override    
//              public void run() {    
//                  Looper.prepare();    
//                  String errorMsg=MessageUtils.getExcptionToastMessage(ex);
//                  Toast.makeText(MainApplication.getInstance(), "很抱歉,程序出现"+errorMsg+",即将退出.",   
//                          Toast.LENGTH_LONG).show();    
//                  Looper.loop();    
//              }   
//          }.start();   
//      }
        Writer writer = new StringWriter();
        PrintWriter printWriter = new PrintWriter(writer);
        ex.printStackTrace(printWriter);

        Throwable cause = ex.getCause();
        while (cause != null) {
            cause.printStackTrace(printWriter);
            cause = cause.getCause();
        }

        String info = writer.toString();
        printWriter.close();
        FileUtil.saveLog("=================CrashInfo===============");
        FileUtil.saveLog(info);
        SLog.Console(info);
        FileUtil.saveLog("================CrashInfoEnd=============");
        return info;
    }

}

然后在MainApplication中添加对应的声明即可

package com.example.zxingdemo;

import android.app.Application;

import com.util.CrashHandler;
import com.util.PathUtil;
import com.util.SLog;

public class MainApplication extends Application {

    private static MainApplication mApplication;

    @Override
    public void onCreate() {
        super.onCreate();
        mApplication = this;
        PathUtil.getInstance().init(mApplication);
        SLog.cleanOutOfDateLog();
        // 添加全局异常捕获
        CrashHandler crashHandler = CrashHandler.getInstance();
        crashHandler.init(getApplicationContext());
    }

    public static synchronized MainApplication getInstance() {
        return mApplication;
    }
}

最后一定要注意在Manifest里边指定Application

<application
        android:name="com.example.zxingdemo.MainApplication"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:screenOrientation="portrait" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.karics.library.zxing.android.CaptureActivity"
            android:theme="@android:style/Theme.NoTitleBar"
            android:screenOrientation="portrait" >
        </activity>
    </application>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值