'How to close a webview app if no activity within 5 minutes?

I am asking this after long searches without help.

I created a simple webview app with eclipse.

(Sometimes – app opens a web browser depending on the url)

I need to kill the app if there are no clicks (not active) within 5 minutes.

Whenever a user clicks on any link in the app – the timer would reset.

I know it should be simple but I’ve got mixed up with too many lines of code… :/

Can anyone be nice and show a code example for how it’s done ?

Thank you dearly

public class MainActivity extends Activity {
private WebView webView;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    final WebView webView = (WebView) findViewById(R.id.webView);
    webView.getSettings().setJavaScriptEnabled(true);

    webView.setWebViewClient(new WebViewClient() {           
       // if url contains url1,2,3 - launch in browser     
       @Override public boolean shouldOverrideUrlLoading(final WebView view, final String url) {
          if(url.contains("url1.com")||(url.contains("url2.com")) ||(url.contains("url3.com"))       ) {
               Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
               startActivity(i);
               return true;

          }
          else {

          view.loadUrl(url);

          return false;
          }
       }
    });

    webView.loadUrl("http://starter-site.com");

}

}


Solution 1:[1]

Use a Handler. Create a Runnable that finishes your activity.

Each time a user clicks a link, do something like this:

myHandler.removeCallbacks(myFinishingRunnable);
myHandler.postDelayed(myFinishingRunnable, 5000);

Be careful not to leak your activity (if your Runnable is an inner class, make it static and give it a WeakReference to your activity). And it's probably a good idea to set/unset the callback when your activity is resumed/paused.

Solution 2:[2]

It seems like I have found a better solution. I decided to kill the app if a specific url string is in use.

So, if the click went on Google, it would simply launch the browser and shut down.

Hope this is ok in the Android way of mind...I guess not.

@Override
public boolean shouldOverrideUrlLoading(final WebView view, final String url) {
    if (url.contains("url1.com") || (url.contains("url2.com")) || (url.contains("url3.com"))) {
        Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        startActivity(i);

        if (url.contains("google")) {
            finish();
        }
        return true;
    } else {
        view.loadUrl(url);
        return false;
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Snild Dolkow
Solution 2 Laurel