0

I'm developing an Android Webview app. I would like to use onbackpressed to go to the previous page but also to exit the app.

How it should work:

  • Pressing back-button on homepage: I want to show a message "Press once again to exit."
  • Pressing back-button on other webpages: it should immediately open the previous page.

I tried to achieve this by using the following code. The only problem is that I don't know how to set my homepage as a variable. Right now I'm getting the error message "Page cannot be resolved as a variable". I understand why I get that message, I just don't know how to solve it in this particular case.

Let's say my homepage url is "http://example.com", how do I set this homepage as a variable?

private Boolean exit = false;
@Override
public void onBackPressed() {
 if(page != "homepage"){
      super.onBackPressed(); // Calls the Overriden Method 
 }
else
{
if (exit)
    this.finish();
else {
    Toast.makeText(this, "Press once again to exit.",
            Toast.LENGTH_SHORT).show();
    exit = true;
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            exit = false;
        }
    }, 3 * 1000);

}
}

}
Stan
  • 937
  • 5
  • 15
  • 33

2 Answers2

0

maybe this will help:

int clickedTwice = 0;
public void onBackPressed() {
if(page != "homepage"){
  super.onBackPressed(); // Calls the Overriden Method 
}
else
{
    clickedTwice++;
    if(clickedTwice == 2)
    {
        super.onBackPressed();
    }
    else
    {
        Toast.makeText(this,"press again to exit",Toast.LENGTH_SHORT).show();
    }

    new Handler().postDelayed(new Runnable()
    {

        @Override
        public void run()
        {
            clickedTwice--; 

        }
    }, 2000);  // will wait for 2 seconds for user's another click!
 }
}

}
Sarthak Mittal
  • 5,794
  • 2
  • 24
  • 44
  • Thanks for the answer! I will give it a try, but how to solve the "Page cannot be resolved to a variable" error message? The line `if(page != "homepage"){` is still causing trouble. – Stan Dec 01 '14 at 13:19
  • you using fragments? though i am not very good at fragments but maybe you can maintain a variable in which you will store which fragment is currently opened and check that variable in the if condition of yours :) – Sarthak Mittal Dec 01 '14 at 13:23
0

You can check isback page for webview then you can write down the code for exist from app. You can use following code for check

if(webView.canGoBack())
{
// your code 
}