android 自定义全局异常捕获UncaughtExceptionHandler

一个APP总会有几个我们人脑忽略掉的异常,所以就需要一个全局异常捕获,来处理这些异常,

一般使用Thread类中唯一的Interface来处理:

    @FunctionalInterface
    public interface UncaughtExceptionHandler {
        /**
         * Method invoked when the given thread terminates due to the
         * given uncaught exception.
         * <p>Any exception thrown by this method will be ignored by the
         * Java Virtual Machine.
         * @param t the thread
         * @param e the exception
         */
        void uncaughtException(Thread t, Throwable e);
    }

直接上代码,方便以后搬砖:

package com.example.myapplication.util;

import android.content.Context;
import android.content.Intent;
import com.example.myapplication.LauncherActivity;
import java.lang.Thread.UncaughtExceptionHandler;

/**
 * 自定义全局异常捕获类
 * 
 * @author Alex
 */
public class CrashHandler implements UncaughtExceptionHandler {

	private Context mContext;
	private static volatile CrashHandler crashHandler;
	private UncaughtExceptionHandler mDefaultHandler;

	// 获取CrashHandler实例 单例模式 - 双重校验锁
	public static CrashHandler getInstance() {
		if (crashHandler == null) {
			synchronized (CrashHandler.class) {
				if (crashHandler == null) {
					crashHandler = new CrashHandler();
				}
			}
		}
		return crashHandler;
	}

	/**
	 * 初始化
	 * @param context
	 */
	public void init(Context context) {
		mContext = context;
		// 静态方法,获取系统默认的UncaughtException处理器,对所有线程都有效
		mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
		// 设置该CrashHandler为程序的默认处理器
		Thread.setDefaultUncaughtExceptionHandler(this);
	}

	@Override
	public void uncaughtException(Thread thread, final Throwable throwable) {
		if (!handleException(throwable) && mDefaultHandler != null) {
			// 如果用户没有处理则让系统默认的异常处理器来处理
			mDefaultHandler.uncaughtException(thread, throwable);
		} else {
			// 打开启动页
			Intent intent = new Intent(mContext, LauncherActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			mContext.startActivity(intent);
			// 杀死该应用进程
			android.os.Process.killProcess(android.os.Process.myPid());
			System.exit(0);
		}
	}

	/**
	 * 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成.
	 *
	 * @param throwable
	 * @return true:如果处理了该异常信息;否则返回false.
	 */
	private boolean handleException(Throwable throwable) {
		if (throwable == null) {
			return false;
		}

		// 此处 收集设备参数信息,保存日志文件
		// todo
		return true;
	}
}

在自定义Application中初始化就可以用了:

public class MyApp extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        CrashHandler.getInstance().init(this);
    }
}

好了,又可以愉快的玩耍了。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值