I wrote a piece of code that will give the user a prompt asking them to press back again if they would like to exit. I currently have my code working to an extent but I know it is written poorly and I assume there is a better way to do it. Any suggestions would be helpful!
Code:
public void onBackPressed(){
backpress = (backpress + 1);
Toast.makeText(getApplicationContext(), " Press Back again to Exit ", Toast.LENGTH_SHORT).show();
if (backpress>1) {
this.finish();
}
}
use to .onBackPressed() to back Activity specify
additionally, you need to dissmis dialog before calling
activity.super.onBackPressed()
, otherwise you'll get "Activity has leaked.." error.Example in my case with sweetalerdialog library:
If you want to exit your application from direct Second Activity without going to First Activity then try this code..`
In Second Activity put this code..
And Your First Activity Put this code.....
}
I would implement a dialog asking the user if they wanted to exit and then call
super.onBackPressed()
if they did.In the above example, you'll need to replace WelcomeActivity with the name of your activity.
This is the best way, because if user not nack more than two seconds then reset backpressed value.
I just had this issue and solved it by adding the following method: