预防android运行时的空指针,下标越界,等等的java异常导致程序Crash.
github:https://github.com/xuuhaoo/DefenseCrash
这个库的作用介绍
预防崩溃库是专门Android端捕获Java崩溃的一个小而美的库,可以通过集成DefenseCrash有效减少Java代码的崩溃,例如在应用程序使用过程中可以避免NPE或IOB崩溃,改善用户体验。
Gradle的配置
- 首先,加入下面的代码到
项目
的build.gradle
中
allprojects {
repositories {
maven { url 'https://dl.bintray.com/xuuhaoo/maven/'}
}
}
- 完成了上面的配置之后,你需要将下面的代码复制到你
模块
的build.gralde中
dependencies {
compile 'com.tonystark.android:defense_crash:2.0.0'
}
下面,初始化这个库
有两种初始化方法可以选择:
- 选择一: 手动的安装这个库,按照如下代码:
public class MyApp extends Application implements IExceptionHandler {
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
// step1: 初始化库
DefenseCrash.initialize();
// setp2: 安装防火墙
DefenseCrash.install(this);
}
@Override
public void onCaughtException(Thread thread, Throwable throwable, boolean isSafeMode) {
// step3: 打印错误堆栈
throwable.printStackTrace();
// step4: 上报该错误到错误收集的平台,例如国内的Bugly,友盟等
}
@Override
public void onEnterSafeMode() {
// 框架使程序运行进入了安全模式,这种情况是在程序运行过程中发生了崩溃,
// 但是不要慌,已经被框架拦截并且进入了安全模式,这里你可以什么都不用做.
}
@Override
public void onMayBeBlackScreen(Throwable throwable) {
// 这个回调说明在onLayout(),onMeasure() 和 onDraw()中出现了崩溃
// 这种崩溃会导致绘图异常和编舞者类崩溃
// 我们建议你在这时候,重启当前的activity或者应用
}
}
- 选择二: 直接将你的Application类继承自DefenseCrashApplication就好了,不用做别的处理
public class MyApp extends DefenseCrashApplication {
//...和上面的一样
}
就此,集成完成啦!
版权
Copyright [2018] [徐昊]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.