Android Exception(全局异常)

来源:互联网 发布:python基础环境搭建 编辑:程序博客网 时间:2024/06/10 15:34

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);            }          }        }      }    });  }

[代码下载]

原创粉丝点击