How to refresh the WebView in android using a Timer?

后端 未结 1 1680
眼角桃花
眼角桃花 2020-12-10 18:18

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

Whether it\'s possible?

相关标签:
1条回答
  • 2020-12-10 19:18

    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);
    
    0 讨论(0)
提交回复
热议问题