Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to refresh the WebView in android using a Timer?

Tags:

android

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

Whether it's possible?

like image 210
Shan Avatar asked Nov 21 '11 08:11

Shan


1 Answers

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);
like image 172
Vito Gentile Avatar answered Nov 20 '22 02:11

Vito Gentile