从被调用2-3次的方法开始,仅在1秒后调用一次方法

时间:2014-03-13 10:46:47

标签: java android android-webview

onReceivedTitle网址更改时,以下方法webview会被调用2-3次。我想在上次调用onReceivedTitle时调用其中的方法。我这样做是因为我只想在webview中监视网址更改。当网址通过ajax更改时,shouldOverrideUrlLoading不会被调用。

class MyWebChromeClient extends WebChromeClient {


        @Override
        public void onReceivedTitle(WebView view, String title) {
            Log.v("onReceivedTitle", "=>" + title);

            // callAMehod();
            super.onReceivedTitle(view, title);
        }

    }

2 个答案:

答案 0 :(得分:3)

如果要限制方法调用引起另一个方法调用的频率,可以通过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)

您可能希望使用Handler并执行以下操作:

class MyWebChromeClient extends WebChromeClient {

    private boolean mOnReceivedTitleInvoked;

    @Override
    public synchronized void onReceivedTitle(final WebView view, final String title) {
        if (!mOnReceivedTitleInvoked) {
            mOnReceivedTitleInvoked = true;
            Log.v("onReceivedTitle", "=>" + title);

            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    super.onReceivedTitle(view, title);
                    mOnReceivedTitleInvoked = false;
                }
            }, 1000);
        }
    }

}

虽然您可能想重新考虑onReceivedTitle行为。