场景描述:产品故意整事,狂点一个页面跳转按钮,然而那个页面的展示时需要初始化一个第三方的SDK,导致一个启动模式为 android:launchMode="singleTop"
的页面Activity重复新建了多次。
1、解决思路查看源码:startActivity(intent);
发现是调用了
@Override
public void startActivity(Intent intent, @Nullable Bundle options) {
if (options != null) {
startActivityForResult(intent, -1, options);
} else {
// Note we want to go through this call for compatibility with
// applications that may have overridden the method.
startActivityForResult(intent, -1);
}
}
也就是说我这边只要重写 startActivityForResult()
方法就好
2、重写 startActivityForResult()
/**
* 每次启动activity都会调用此方法
*/
@SuppressLint("RestrictedApi")
@Override
public void startActivityForResult(Intent intent, int requestCode, @Nullable Bundle options) {
if (!isFastClick()) {
super.startActivityForResult(intent, requestCode, options);
}
}
可能注意到了if (!isFastClick()) {}
,就是在这做判断
3、判断是否快速点击 isFastClick()
/**
* 检查是否重复跳转,不需要则重写方法并返回true
*/
// 两次点击间隔不能少于1000ms
private static final int FAST_CLICK_DELAY_TIME = 1000;
private static long lastClickTime;
public static boolean isFastClick() {
boolean flag = true;
long currentClickTime = System.currentTimeMillis();
if ((currentClickTime - lastClickTime) >= FAST_CLICK_DELAY_TIME ) {
flag = false;
}
lastClickTime = currentClickTime;
return flag;
}