对于异常的捕捉

本文介绍了一个自定义的异常处理程序,该程序能在应用程序遇到未捕获异常时收集错误信息并重启应用。文章详细展示了如何使用Java实现这一过程,包括记录异常详情、通知用户以及通过定时器触发应用重启。

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

   public class CrashHandler implements UncaughtExceptionHandler {
    TAppliction tAppliction;

    public CrashHandler(TAppliction tAppliction) {
        this.tAppliction = tAppliction;
    }

    // 程序任何地方,出了异常,没加catch, 就会执行uncaughtException
    @Override
    public void uncaughtException(Thread thread, Throwable ex) {

        // 收集异常信息
        String info = ex.getMessage();
        Log.i("uncaughtException", "info=" + info);

        StringWriter stringWriter = new StringWriter();

        PrintWriter printWriter = new PrintWriter(stringWriter);
        // 详细异常信息打印到printWriter, printWriter又把信息打到StringWirter, 通过stringWriter转成string
        ex.printStackTrace(printWriter);
        info = stringWriter.toString();
        Log.i("uncaughtException", "info=" + info);

        // 联网发送给服务器,
        // 开发人员通过服务器随时看异常信息

        // toast告诉用户重启
        new Thread() {
            public void run() {
                Looper.prepare();//创建looper
                Toast.makeText(tAppliction, "抱歉,程序将重启", Toast.LENGTH_LONG)
                        .show();
                Looper.loop();
            };
        }.start();

        Log.i("uncaughtException", "toast执行完了");
        //一旦杀进行就得用到这个代码;
        try {
            Thread.currentThread().sleep(2000);
        } catch (Exception e) {
            // TODO: handle exception
        }

        // 实现重启功能
//0x10000000
        Intent intent = new Intent(tAppliction, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(tAppliction,
                100, intent, Intent.FLAG_ACTIVITY_NEW_TASK);

        // 定时器
        AlarmManager manager = (AlarmManager) tAppliction.getSystemService(Context.ALARM_SERVICE);

        manager.set(AlarmManager.RTC, System.currentTimeMillis() + 2000,pendingIntent);
        tAppliction.finishActivity();

    }

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值