0. 前言
一般的Android应用只是对Crash进行捕捉。而Sunzxyong大神的Recovery框架,能做到对Crash进行捕捉并自动恢复。大大地提高APP的用户体验。
本文意在分析Recovery框架的三个关键点,让大家了解其实现原理。
Github地址:https://github.com/Sunzxyong/Recovery
1. 捕获异常
通过实现并注册接口 Thread.UncaughtExceptionHandler,处理没有被try-catch捕获的异常。
public class MyCrashHandler implements Thread.UncaughtExceptionHandler {
@Override
public void uncaughtException(Thread t, Throwable e) {
// 处理异常:打印异常信息,恢复Activity栈
}
// 在外部调用,注册异常捕捉
public static void register() {
Thread.setDefaultUncaughtExceptionHandler(new MyCrashHandler());
}
}
2. 维护私有的Activity栈
通过在Application里调用registerActivityLifecycleCallbacks()进行注册,监听Activity的创建和销毁,自己维护一个Activity的栈。使用要求:API 14+
public class RecoveryActivityLifecycleCallback implements Application.ActivityLifecycleCallbacks {
@Override
public void onActivityCreated(final Activity activity, Bundle savedInstanceState) {
}
@Override
public void onActivityStarted(final Activity activity) {
.... 省略一些判断 .....
Window window = activity.getWindow();
if (window != null) {
View decorView = window.getDecorView();
if (decorView == null)
return;
decorView.post(new Runnable() {
@Override
public void run() {
// Activity进栈
RecoveryStore.getInstance().putActivity(activity);
Object o = activity.getIntent().clone();
RecoveryStore.getInstance().setIntent((Intent) o);
}
});
}
}
@Override
public void onActivityResumed(Activity activity) {
}
@Override
public void onActivityPaused(Activity activity) {
}
@Override
public void onActivityStopped(Activity activity) {
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
@Override
public void onActivityDestroyed(Activity activity) {
// Activity出栈
RecoveryStore.getInstance().removeActivity(activity);
}
}
注册全局的Activity监听
((Application) mContext).registerActivityLifecycleCallbacks(new RecoveryActivityLifecycleCallback());
3. 恢复Activity栈
崩溃时,通过startActivities()来启动多个Activity,从而恢复Activity栈
private void recoverActivityStack() {
ArrayList<Intent> intents = getRecoveryIntents();
if (intents != null && !intents.isEmpty()) {
ArrayList<Intent> availableIntents = new ArrayList<>();
for (Intent tmp : intents) {
if (tmp != null && RecoveryUtil.isIntentAvailable(this, tmp)) {
tmp.setExtrasClassLoader(getClassLoader());
availableIntents.add(tmp);
}
}
if (!availableIntents.isEmpty()) {
availableIntents.get(0).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
availableIntents.get(availableIntents.size() - 1).putExtra(RECOVERY_MODE_ACTIVE, true);
startActivities(availableIntents.toArray(new Intent[availableIntents.size()]));
overridePendingTransition(0, 0);
finish();
return;
}
}
restart();
}
4. 存在的问题
在多进程并共用同一个任务栈的APP中,因为每个进程内存都是独立的,无法把不同进程的Activity放到同一个List里。所以在恢复Activity任务栈时会出现问题。
解决方法:对Activty栈使用本地文件来保存,实现跨进程共享。