Thread.UncaughtExceptionHandler捕获异常

本文详细介绍了一种自定义CrashHandler的实现方法,通过继承Thread.UncaughtExceptionHandler接口,实现了程序异常捕获与处理功能。文章展示了如何初始化CrashHandler实例,设置默认的异常处理器,并在异常发生时进行自定义错误信息的记录与展示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.prisoner.prisoner.thread;

import android.content.Context;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import static android.support.constraint.Constraints.TAG;

public class CrashHandler implements Thread.UncaughtExceptionHandler {
private static CrashHandler instance;
private Context mContext;
private Thread.UncaughtExceptionHandler uncaughtExceptionHandler;

public static synchronized CrashHandler getInstance(){
    if (instance==null){
        instance=new CrashHandler();
    }
    return instance;
}
public void init(Context context){
    mContext=context;
    uncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
    Thread.setDefaultUncaughtExceptionHandler(this);
}
private void addCustomInfo() {
    Log.i(TAG, "addCustomInfo: 程序出错了...");
}

private boolean handleExceptiion(Throwable ex){
    if (ex==null){
        return false;
    }
    addCustomInfo();
    new Thread(){
        @Override
        public void run() {
            Looper.prepare();
            Toast.makeText(mContext, "程序开小差了呢..", Toast.LENGTH_SHORT).show();
            Looper.loop();
        }
    }.start();
    return true;
}
@Override
public void uncaughtException(Thread t, Throwable e) {
    if (!handleExceptiion(e)&&uncaughtExceptionHandler!=null){
        uncaughtExceptionHandler.uncaughtException(t,e);
    }else {
        try {
            Thread.sleep(3000);
        }catch (Exception es){
            Log.e(TAG, "error : ", es);
        }
    }
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值