0

first of all sorry for my english. i am new at android and working on app. my app has 8 activities and they usually starting by click and like this, activity1-> 2->3->4->5->6->7->activity8 .
as usual, when i press the back button 7 times and it closes activities act8 to act1. if i am at activty1 back button closes the app. i want to make a alerdiaolog there to alert me like "it is your last activity!!". but when i use public void onBackPressed() command to show diaolog such as" are u sure to exit ?" , it is not only prevent app closing, it is also prevent closing the other activies, for example if i am at the 8th activity i cant go back to 7th activity, app shows me alert dialog "are u sure to exit ?"

to sum up;
- where should i put the public void onBackPressed() code , if i want to prevent only closing app except activies?
- can i use code like this , if(myactivity is the lastone or main activity ) { "are sure to exit the app ?"}

Sorry for language again, thank you for your interest.

2 Answers2

1

You should keep onBackPressed() as it is in your activities 2 to 8 and in activity 1 override onBackPressed() as below.

@Override
public void onBackPressed() {
    new AlertDialog.Builder(this)
           .setMessage("Are you sure you want to exit?")
           .setCancelable(false)
           .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                   finish();
               }
           })
           .setNegativeButton("No", null)
           .show();
}
karan
  • 8,637
  • 3
  • 41
  • 78
1

If you are not finishing your first activity whenever you stat new activity this solution works. In last activitiy's onBackpress() write following

@Override
    public void onBackPressed() {
        //show your alert here and in alert's conform you should call finish()
    }
Mirza Ahmed Baig
  • 5,605
  • 3
  • 22
  • 39