快速点击可能带来的问题:
1.同一个接口调用多次
2.相同的activity启动多个
针对上面2个问题,参照了2篇文章,给出我认为比较好的解决方案。
参考:https://www.jianshu.com/p/06c5b35b4e51
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (AntiShakeUtils.isInvalidClick(v)) {
return;
}
//TODO 你要调用的接口或者其他事情
}
});
AntiShakeUtils 类:
import android.support.annotation.IntRange;
import android.support.annotation.NonNull;
import android.view.View;
import com.vwiov.vwiovdriverapp.R;
/**
* 防抖动点击
*
Email:[email protected]
*
QQ:1006368252
*
https://github.com/JustinRoom/JSCKit
*
* @author jiangshicheng
*/
public class AntiShakeUtils {
private final static long INTERNAL_TIME = 1000;
/**
* Whether this click event is invalid.
*
* @param target target view
* @return true, invalid click event.
* @see #isInvalidClick(View, long)
*/
public static boolean isInvalidClick(@NonNull View target) {
return isInvalidClick(target, INTERNAL_TIME);
}
/**
* Whether this click event is invalid.
*
* @param target target view
* @param internalTime the internal time. The unit is millisecond.
* @return true, invalid click event.
*/
public static boolean isInvalidClick(@NonNull View target, @IntRange(from = 0) long internalTime) {
long curTimeStamp = System.currentTimeMillis();
long lastClickTimeStamp = 0;
Object o = target.getTag(R.id.last_click_time);
if (o == null){
target.setTag(R.id.last_click_time, curTimeStamp);
return false;
}
lastClickTimeStamp = (Long) o;
boolean isInvalid = curTimeStamp - lastClickTimeStamp < internalTime;
if (!isInvalid)
target.setTag(R.id.last_click_time, curTimeStamp);
return isInvalid;
}
}
参考:https://blog.csdn.net/ziyexiaoxiao/article/details/85292729
将下面的内容在BaseActivity里定义就好。
/**
* 每次启动activity都会调用此方法
*/
@SuppressLint("RestrictedApi")
@Override
public void startActivityForResult(Intent intent, int requestCode, @Nullable Bundle options) {
if (checkDoubleClick(intent)) {
super.startActivityForResult(intent, requestCode, options);
}
}
private String mActivityJumpTag; //activity跳转tag
private long mClickTime; //activity跳转时间
/**
* 检查是否重复跳转,不需要则重写方法并返回true
*/
protected boolean checkDoubleClick(Intent intent) {
// 默认检查通过
boolean result = true;
// 标记对象
String tag;
if (intent.getComponent() != null) { // 显式跳转
tag = intent.getComponent().getClassName();
}else if (intent.getAction() != null) { // 隐式跳转
tag = intent.getAction();
}else {
return true;
}
if (tag.equals(mActivityJumpTag) && mClickTime >= SystemClock.uptimeMillis() - 500) {
// 检查不通过
result = false;
}
// 记录启动标记和时间
mActivityJumpTag = tag;
mClickTime = SystemClock.uptimeMillis();
return result;
}
针对fragment 点击跳转问题,只需要在承载它的activity调用上面的方法就可以的,当然集成BaseActivity的不需要处理!
如果碰到个别activity还是会启动相同,别的activity不会的情况。
排查下对应activity的onCreate,onStart,onResume是否进行了耗时操作,耗时操作异步处理!
原因:
A跳转到B,需要经历A的onPause,B的onCreate,onStart,onResume,所以在这几个方法中不能做耗时的操作。