实用工具----基于UncaughtExceptionHandler实现的奔溃日志捕获显示、分享的封装

今天我们介绍主角是UncaughtExceptionHandler,一个Java提供给我们的用于全局监听奔溃信息回调的接口类。下面我们就来具体看下其使用方法,并对其进行封装,方便项目直接使用。

UncaughtExceptionHandler介绍

UncaughtExceptionHandler是定义在Thread类中的一个内部接口,该接口只有uncaughtException一个回调方法。

    @FunctionalInterface
    public interface UncaughtExceptionHandler {
        //奔溃异常时的回调方法
        void uncaughtException(Thread t, Throwable e);
    }

UncaughtExceptionHandler的使用

step 1:  我们定义一个类MyUncaughtExceptionHandler实现UncaughtExceptionHandler

/**
 * Created by chendx on 2018/6/30
 *
 * @since 1.0
 */
public class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler{
    private Thread.UncaughtExceptionHandler uncaughtExceptionHandler;
    public MyUncaughtExceptionHandler(Thread.UncaughtExceptionHandler uncaughtExceptionHandler) {
        this.uncaughtExceptionHandler = uncaughtExceptionHandler;
    }

    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        //------处理异常逻辑开始-------

             //....此处省略一万行代码

        //------处理异常逻辑结束-------
        if (uncaughtExceptionHandler != null) {
            uncaughtExceptionHandler.uncaughtException(thread, ex);
        }
    }
}

step 2:  初始化MyUncaughtExceptionHandler(一般放在Application的onCreate中完成)

  Thread.UncaughtExceptionHandler handler = Thread.getDefaultUncaughtExceptionHandler();
  MyUncaughtExceptionHandler exceptionHandler = new MyUncaughtExceptionHandler(handler);
  Thread.setDefaultUncaughtExceptionHandler(exceptionHandler);

通过以上步骤,我们就可以很愉快地接收App崩溃异常信息了。在uncaughtException中我们可以用一个界面将奔溃信息进行展示,也可以将奔溃信息存储到本地或者服务器等。

基于UncaughtExceptionHandler的封装---CrashHandlerLib库

介绍:一个基于UncaughtExceptionHandler实现的Android奔溃日志捕获依赖库,使用该库可以显性的将奔溃日志展示出来,有助于开发以及测试人员在工作中及时定位奔溃问题.同时支持将奔溃日志分享到微信、QQ等第三方。

使用手册

step 1.在根目录 build.gradle 上添加配置

allprojects {
	repositories {
		...
		maven { url 'https://jitpack.io' }
	}
}

step 2.在当前module的build.gradle添加如下依赖

dependencies {
	com.github.CrazyCoder01:CrashHandler:v2.0'
}

step 3.在Application中完成初始化

@Override
public void onCreate() {
    super.onCreate();
    CrashManager.getInstance().init(this, BuildConfig.DEBUG);
}

效果演示

step 1.测试代码源码

1>>>奔溃日志文件分享到QQ、微信等第三方:
 CrashManager.getInstance().shareCrashFile(MainActivity.this);
2>>>类型为TextView的test2控件没有findViewById导致奔溃
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    test = findViewById(R.id.test);

   test.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d("cdx", test2.getText().toString());
        }
    });

    findViewById(R.id.share_crash_file).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //将奔溃信息分享到第三方
            CrashManager.getInstance().shareCrashFile(MainActivity.this);
        }
    });
}

step 2.运行查看效果

猜你喜欢

转载自blog.csdn.net/tuike/article/details/80825993