如何在android中使用定时器刷新WebView



是否可以设置定时器,仅当应用程序当前处于活动状态时,每1分钟刷新一次webview ?

是否可能?

首先,您需要创建一个TimerTask类:

protected class ReloadWebView extends TimerTask {
    Activity context;
    Timer timer;
    WebView wv;
    public ReloadWebView(Activity context, int seconds, WebView wv) {
        this.context = context;
        this.wv = wv;
        timer = new Timer();
        /* execute the first task after seconds */
        timer.schedule(this,
                seconds * 1000,  // initial delay
                seconds * 1000); // subsequent rate
        /* if you want to execute the first task immediatly */
        /*
        timer.schedule(this,
                0,               // initial delay null
                seconds * 1000); // subsequent rate
        */
    }
    @Override
    public void run() {
        if(context == null || context.isFinishing()) {
            // Activity killed
            this.cancel();
            return;
        }
        context.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                wv.reload();
            }
        });
    }
}

在你的Activity中,你可以使用这一行:

new ReloadWebView(this, 60, wv);

最新更新