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);
            }
          }
        }
      }
    });
  }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容