Android Exception(全局异常)

  1. Android 中全局未捕获的异常获取,首先继承UncaughtExceptionHandler,并实现其uncaughtException(Thread thread, Throwable throwable)方法,在此方法中可以打印出具体的错误。
/**
 * 处理异常信息Handler
 * Created by mazaiting on 2017/9/12.
 */
public class CrashHandler implements UncaughtExceptionHandler {
  @Override public void uncaughtException(Thread thread, Throwable throwable) {
    Log.e("TAG", throwable.getMessage());
  }
  1. 点击时我们获取到错误信息之后,程序依然会崩溃,此时我们需要在自己的CrashHandler初始化的时候创建一个Handler,并在MainLooper中执行任务,任务中死循环一个Looper.loop(),在Looper.loop()抛出异常时调用uncaughtException(Thread thread, Throwable throwable)方法,这样就可以做到点击无效果,并可以捕获到异常了。
  /**
   * 初始化
   */
  public void init() {
    // 处理点击后无反应的状态
    new Handler(Looper.getMainLooper()).post(new Runnable() {
      @Override public void run() {

        while (true) {
          try {
            Looper.loop();
          } catch (Throwable e) {
            if (mHandler != null) {
              mHandler.uncaughtException(Looper.getMainLooper().getThread(), e);
            }
          }
        }
      }
    });
  }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值