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(); } }
In order to check when the 'BACK' button is pressed, use onBackPressed() method from the Android library. Next, perform a check to see if the 'BACK' button is pressed again within 2 seconds and will close the app if it is so. Otherwise, don't exit.
I would implement a dialog asking the user if they wanted to exit and then call super.onBackPressed()
if they did.
@Override public void onBackPressed() { new AlertDialog.Builder(this) .setTitle("Really Exit?") .setMessage("Are you sure you want to exit?") .setNegativeButton(android.R.string.no, null) .setPositiveButton(android.R.string.yes, new OnClickListener() { public void onClick(DialogInterface arg0, int arg1) { WelcomeActivity.super.onBackPressed(); } }).create().show(); }
In the above example, you'll need to replace WelcomeActivity with the name of your activity.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With