如何刷新Android的使用定时器的WebView?定时器、Android、WebView

2023-09-12 08:06:49 作者:从心开始

是否定时器可以被设置为刷新web视图每隔1分钟只有当应用程序当前是活动的

Whether a timer can be set to refresh the webview every 1 min only if the application is currently active?

无论是可能的吗?

推荐答案

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

First of all, you need to create a TimerTask class:

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();
            }
        });
    }
}

在你的活动,您可以使用此行:

In your Activity, you can use this line:

new ReloadWebView(this, 60, wv);