2

I want to start another activity in finish() depending on a condition. I got the same code working in onDestroy() but I think this is not the right place from the lifecycle point of view.

(Activities might be destroyed, although there were not actively left by the user).

The following code did not have any effect:

@Override
public void finish() {
    if (mCondition) {
        Intent intent = new Intent(this, OtherActivity.class);
        startActivity(intent);
    }
    super.finish();
}

Why is it not working, are there alternatives?

Mahoni
  • 7,088
  • 17
  • 58
  • 115
  • What did you do to trigger this? Are you certain `finish()` is being called. If it is, was there a an error printed in the log? – Philip Couling Aug 13 '14 at 16:51
  • @couling You are right, finish it not being called, I haven't done it explicitly yet. – Mahoni Aug 13 '14 at 16:54
  • @Mahoni : why don't you try this in `onPause()` any specific reason – Kaushik Aug 13 '14 at 17:16
  • please see the accepted answer of [what exactly Activity.finish() method is doing?](http://stackoverflow.com/questions/10847526/what-exactly-activity-finish-method-is-doing) – Kaushik Aug 13 '14 at 17:22
  • Are you calling finish() at any given point in your application? If not, then this method will not be called since it is not part of the Activity lifecycle. That is why it works in onDestroy() which is part of the lifecycle. Can I ask what workflow you want in your application - that would make it easier to help you. – Dyrborg Aug 13 '14 at 18:18

2 Answers2

1

I think the best option is starting the new activity then finish the current one:

if (mCondition) {
    Intent intent = new Intent(this, OtherActivity.class);
    startActivity(intent);
    finish();
}
Jorgesys
  • 124,308
  • 23
  • 334
  • 268
  • But then it wouldn't be finished on other occasions, would it? I see no difference between this code and mine, except that a plain invocation to `finish()` instead of `super.finish()` would lead to infinite recursion. – Mahoni Aug 13 '14 at 16:48
  • 1
    It's not the most clear answer. The difference is where this code is placed. The suggestion is to move the code out of the `finish()` function and into whatever functions call it. – Philip Couling Aug 13 '14 at 16:53
  • @Mahoni, would lead to infinite recursion and in your code you are finishing the activity before starting the new one. http://stackoverflow.com/questions/18957125/how-to-finish-activity-when-starting-other-activity-in-android – Jorgesys Aug 13 '14 at 17:04
0

I have Used Myself this and it is working fine

   public void ToBeClosed()
    {
        Intent a = new Intent(context,NewActivity.class);
        startActivity(a);
        OldActivity.this.finish();
    }

and use the function in if statement body

 if (mCondition) { ToBeClosed(); }
Jamil
  • 5,457
  • 4
  • 26
  • 29