9

I have a program. The first activity is a splash screen and the second is the log in and the third is a list view menu activity, and then 2 other activities. The splash screen disappear after 3 seconds and if the log in check box remember me is checked, it goes directly to the menu page.
I override the onBackPressed function in the menu activity so that it will exit the program directly after the user click back from the menu. However, if I have gone through the other activities it doesn't exit; it goes to the previous activity in the stack and the dialog box doesn't pop up, although it actually does appear for a second no less and disappear right away.

Here is my onBackPressed function

public void onBackPressed() {
    // super.onBackPressed();
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Are you Sure want to close the Application..?")
        .setCancelable(false)
        .setTitle("EXIT")
        .setNegativeButton("No", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
            }
        })
        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                finish();
            }
        });
    AlertDialog alert = builder.create();
    alert.show();
    //super.onBackPressed();
}
stealthjong
  • 10,858
  • 13
  • 45
  • 84
user2401745
  • 357
  • 2
  • 5
  • 12

6 Answers6

9

Update - 19th June 2022

The below answer is outdated. We can use the navigation architecture components with toolbar so the back navigation is handled for us or you should check https://developer.android.com/guide/navigation/navigation-custom-back

For navigation architecture components check

https://developer.android.com/guide/navigation/navigation-getting-started

Navigation components are available for compose as well https://developer.android.com/jetpack/compose/navigation

Old Answer - Outdated

I would suggest you to use ActionBar as suggested by WarrenFaith in the comments below. Pls check the link below for more information

http://developer.android.com/design/patterns/navigation.html

Here's a tutorial for the same

http://www.vogella.com/articles/AndroidActionBar/article.html

You can use this. However this also seems to be a bad design. You can check the comments below to know why

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        onBackPressed();
    }
    return super.onKeyDown(keyCode, event);
}

public void onBackPressed() {
    Intent myIntent = new Intent(MyActivity.this, MainActivity.class);

    myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(myIntent);
    finish();
    return;
}

Onn back button pressed inn your current activity when you back press you clear the activity stack and naviagate to MainActivity.

Also i would suggest no to display a alert dialog on back button press. Its a bad design. You can search on SO. i read the same and was answered by commonsware

Raghunandan
  • 132,755
  • 26
  • 225
  • 256
  • Wait a moment. You are talking about a "close"-dialog being a bad design but in the same moment you suggest to open a new Activity instead? Are you kidding me? This is even worse than a dialog asking if I hit the back button by accident... A back button should at least bring me *back* and not into a newly created activity! – WarrenFaith May 22 '13 at 13:32
  • @WarrenFaith i agree with what you say. I know by default it should work like that. But since the OP was asking for the same i posted it. – Raghunandan May 22 '13 at 13:35
  • Still one of the worst UX experience you can create. I will therefore keep the down vote. – WarrenFaith May 22 '13 at 13:37
  • 3
    In fact that is where a so called "navigation" structure comes into the scene and tells you: "hey, you can use the back button, but if you want to go to home, just press the icon in my actionbar and you are back at home". Even the new SlideMenu would be a good UX solution. And yes: I would expect it to go 40 screens back as it is the reason the back button exists. Do you expect the back button in your browser to bring you to the start page? Where do you differ between "the user wants to go one step back" or "he wants to go all the way back"? I hope I made it clear... – WarrenFaith May 22 '13 at 13:48
  • @WarrenFaith its clear. I just wanted some clarification that's all. I am editing my answer – Raghunandan May 22 '13 at 13:51
  • @WarrenFaith i edited my answer and provided to link to the user doc site. I went through the link. You are right its a bad design. thanks for letting me know. This will help me suggest better answer in the future for same kind of questions. Learnt something new – Raghunandan May 22 '13 at 13:58
  • @WarrenFaith thanks for your support and detailed info of the topic – Raghunandan May 22 '13 at 14:03
  • @WarrenFaith could you pls check this question and answer in the link. have i suggested in the right way http://stackoverflow.com/questions/16709618/how-to-close-all-activities-while-pressing-hardware-home-button/16709885#comment24055228_16709885 – Raghunandan May 23 '13 at 09:47
2

You can override back button like this

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        // write your code here
    }
    return true;
}
stealthjong
  • 10,858
  • 13
  • 45
  • 84
2
@Override
public void onBackPressed() {
    super.onBackPressed();
    int count = getSupportFragmentManager().getBackStackEntryCount();
    Log.e("count", "is getBackStackEntryCount -> " + count);
    for (int i = 0; i < count; ++i) {
        getSupportFragmentManager().popBackStackImmediate();
        Log.e("getBackStack", "IS REMOVED " + i);
    }
    // toolbar.setTitle("Dashboard");
}
stealthjong
  • 10,858
  • 13
  • 45
  • 84
Keshav Gera
  • 10,807
  • 1
  • 75
  • 53
0

Removing the finish(); after every startActivity(); will allow for proper navigation instead of having to call finish(); that executes the method onDestroy() . Thank u . No need to override the onBackPressed function . Use finish() only when your activity is no longer needed and should be closed .

0

Try this instead of onBackPressed if you are using android.support.v7.app.ActionBar:

    @Override
    public boolean onSupportNavigateUp() {
        // do your stuff

        return super.onSupportNavigateUp();
    }
Asaye
  • 131
  • 1
  • 3
0

Solution for onBackKeypress() and show Dialog. if you use any method like onkeyDown OR onKeyUp , in that please check Back key is not used in that. if used than overide that key or simply removed from there.

Nishith Darji
  • 301
  • 3
  • 5