一.问题抛出
-
android运行的时候难免会有一些空指针(NullPointerException)或者下标越界(IndexOutOfBoundsException),用户使用的过程操作某一个按钮的时候,就发生了崩溃.这时候可能还没有到他感兴趣的部分,程序就Crash掉了,因此导致了用户流失
-
在集成一些第三方库的时候,我们不能修改里面的实现(例如 Gson,FastJson,OkHttp,OkSocket,Glide)等,那么如果他们里面抛出异常如何解决,Glide加载图片之后填充图片时,如果Activity销毁就会造成崩溃,那么我们如何解决?
二.解决效果
预防崩溃演示效果图.gif三.解决思路
- MainLooper一定要保证在崩溃的时候持续Loop
- 子线程发生崩溃,保证主线程Looper继续Loop
- 当绘制,测量,布局出现问题导致编舞者Crash时,应该及时处理(关闭当前异常的界面)
- 生命周期方法发生了异常,在ActivityThread里面hook其中的Instrumentation.进行代理.
- 对ActivityThread中的mH 变量添加Callback,对于不能再Instrumentation中处理的异常进行再次Catch.最大限度保证不崩溃.
四.成品Library
Github项目地址: https://github.com/xuuhaoo/DefenseCrash (欢迎Star)
集成方法:
- Please add the code into your project gradle file
allprojects {
repositories {
maven { url 'https://dl.bintray.com/xuuhaoo/maven/'}
}
}
- Make sure you already done with above instructions in project gradle
files, than you need put this into Module build.gradle file
dependencies {
compile 'com.tonystark.android:defense_crash:2.0.0'
}
We provide you two options for choosing:
- Options 1: You should manually install the defense as following code
public class MyApp extends Application implements IExceptionHandler {
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
// step1: Initialize the lib.
DefenseCrash.initialize();
// setp2: Install the fire wall defense.
DefenseCrash.install(this);
}
@Override
public void onCaughtException(Thread thread, Throwable throwable, boolean isSafeMode) {
// step3: Print the error when crashed during runtime.
throwable.printStackTrace();
// step4: Upload this throwable to your crash collection sdk.
}
@Override
public void onEnterSafeMode() {
// We enter the safe mode to keep the main looper loop after crashed.You’d better do nothing here,we just notify you.
}
@Override
public void onMayBeBlackScreen(Throwable throwable) {
// onLayout(),onMeasure() or onDraw() has breaks down,
// it causes the drawing to be abnormal and the choreographer to break down.
// We will notify you on this method,you’d better finish this activity or restart the application.
}
}
- Options 2: To facilitate some users, we provide a DefenseCrashApplication super class for you to integrate,as following code
public class MyApp extends DefenseCrashApplication {
@Override
public void onCaughtException(Thread thread, Throwable throwable, boolean isSafeMode) {
// step1: Print the error when crashed during runtime.
throwable.printStackTrace();
// step2: Upload this throwable to your crash collection sdk.
}
@Override
public void onEnterSafeMode() {
// We enter the safe mode to keep the main looper loop after crashed.You’d better do nothing here,we just notify you.
}
@Override
public void onMayBeBlackScreen(Throwable throwable) {
// onLayout(),onMeasure() or onDraw() has breaks down,
// it causes the drawing to be abnormal and the choreographer to break down.
// We will notify you on this method,you’d better finish this activity or restart the application.
}
}
网友评论