Using onbackpressed on homepage to exit app, setting homepage variable

444 Views Asked by At

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

}
}

}
2

There are 2 best solutions below

2
On

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!
 }
}

}
0
On

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 
}