如果您想要限制方法调用导致另一方法调用的频率,您可以通过例如Handler
进行调用。最简单的版本在第一次调用和任何后续调用中排队延迟消息,而入队消息不会入队。这导致每X时间需要1次呼叫 - 但至少需要等待第一个动作发生的时间。
实现示例(你可以把你的代码,类未修改的地方)
public abstract class ThrottleExecutor {
private final long mMinDelay;
public ThrottleExecutor(long minDelay) {
mMinDelay = minDelay;
}
/** Implement to do something */
public abstract void doThrottled();
public final void scheduleExecution() {
if (mHandler.hasMessages(0)) {
// message already enqueued, do nothing
} else {
// otherwise enqueue a message for later
mHandler.sendEmptyMessageDelayed(0, mMinDelay);
}
}
public final void cancelExecution() {
mHandler.removeMessages(0);
}
private final Handler mHandler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message msg) {
doThrottled();
}
};
}
,然后用它例如像这样
class Usage {
private ThrottleExecutor mThrottle = new ThrottleExecutor(2000) {
@Override
public void doThrottled() {
// happens at most every 2000ms
methodToBeThrottled();
}
};
void methodThatHappensTooOften() {
mThrottle.scheduleExecution();
}
void methodToBeThrottled() {
Log.d("TAG", "triggered at 2000ms before");
}
}
,你会怎么去理解这是否是最后一次通话或不? –
每当1秒或2秒后第一次调用方法时,它将是最后一次肯定。所以基本上我想使用像定时器的东西。 – Sunny
你可以使用Thread.sleep(6 * 1000);即1秒并尝试? –