13

I know that I can override the onKeyDown method, but I want Back to do it's thing, just twice!

Anthony Mastrean
  • 21,850
  • 21
  • 110
  • 188
Sara
  • 3,733
  • 6
  • 26
  • 30
  • There's an [Android Devlopers' blog post](http://android-developers.blogspot.com/2009/12/back-and-other-hard-keys-three-stories.html) about using the back key. Just set it up to go back to whichever activity you want. – Donal Rafferty Apr 07 '10 at 13:22

3 Answers3

22

FirstActivity

Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
startActivity(intent);

SecondActivity

int REQUEST_CODE = 123
Intent intent = new Intent(SecondActivity.this, ThirdActivity.class);
startActivityForResult(intent, REQUEST_CODE);

(to make this pedagogic there is more code for this activity below)

ThirdActivity

@Override
public void onBackPressed() {
    // Semi ugly way of supporting that back button takes us back two activites instead of the usual one.
    setResultOkSoSecondActivityWontBeShown();
    finish();   
}

private void setResultOkSoSecondActivityWontBeShown() {
    Intent intent = new Intent();
    if (getParent() == null) {
    setResult(Activity.RESULT_OK, intent);
    } else {
        getParent().setResult(Activity.RESULT_OK, intent);
    }
}

SecondActivity (again)

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 123) {
        if (resultCode == RESULT_OK) {
            finish();
        }
    }
}
Anthony Mastrean
  • 21,850
  • 21
  • 110
  • 188
riper
  • 833
  • 1
  • 9
  • 17
3

I am thinking of it this way:

A -> B -> C

A, B, C activities.

You can't do a back twice since the first onKeyDown() will be executed in C and the second one should be executed in B.

I don't know why you are trying to do, but here are some options.

  1. Using the android:noHistory tag:

    Perhaps your C activity is doing something that doesn't need a view and that's why you want to back twice.

  2. Using an intent. Something like:

    Intent intent = new Intent(C.this, A.class);
    startActivity(intent);
    
  3. Using the finishActivityFromChild(). I have never try it, but it looks like you can use it to decide what to do on B depending of how C ended.

Sufian
  • 6,405
  • 16
  • 66
  • 120
Macarse
  • 91,829
  • 44
  • 175
  • 230
0

|*| Going back one screen or end activity :

finish();

|*| Going back more than one screen :

You can go back to which ever screen you need using intent and use flags to prevent going back to same screen :

Intent gotoScreenVar = new Intent(goFromScreenCls.this, goToScreenCls.class);

gotoScreenVar.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);

startActivity(gotoScreenVar);
Sujay U N
  • 4,974
  • 11
  • 52
  • 88