Harshul Pandav
Harshul Pandav

Reputation: 1036

Android Activity Flow

I have two Activities, say A1 and A2. sequence being A1->A2 From A1 I start A2 without calling finish() in A1. After I press the back button in A2 I want to trigger a function in A1. However, if I use onResume() in A1, the function is triggered even during the start of activity A1, which I want to avoid. It should only be called during the 'back' press of A2.

Upvotes: 1

Views: 664

Answers (4)

Deva
Deva

Reputation: 3949

onResume will always be invoked no matter if its the 1st time or its a restart. You can achieve the same by overriding onRestart()

Edit 1:

Use startActivityForResult instead as suggested by other users.

Upvotes: -1

Hitendra
Hitendra

Reputation: 3226

Here is the other approach(one is as per Dimitar).

public class A extends Activity {
    public static boolean isCalledFromB = false;

    public void onCreate(Bundle instance) {
        isCalledFromB = false;
    }

    public void onResume()
    {
        if(isCalledFromB)
            dosomething();

    }

    public void dosomething() {

    }

}

public class B extends Activity {
..............

    public boolean onKeyDown(int keycode, KeyEvent event) {
        if (keycode == KeyEvent.KEYCODE_BACK) {
            A.isCalledFromB=true;
            finish();
        } 
        return true;
    }

}

Upvotes: 1

Dimitar Dimitrov
Dimitar Dimitrov

Reputation: 564

Well start A2 with startActivityForResult then in

A1 implement

  @Override
  public void onActivityResult(final int requestCode, int resultCode, final Intent data) {

   // your code here

}

in A2 override onBackPresset to set result before finishing the activity. Thats it.

Upvotes: 4

Paresh Mayani
Paresh Mayani

Reputation: 128428

Then override onBackPressed() method inside the A2 Activity.

FYI: It works in Android 2.x otherwise you can use onKeyDown() in Android 1.x

2nd Way:

Start A2 activity inside the Activity A1 by using startActivityForResult(). So when you press back key, it will redirect you to onActivityResult() inside the A1 activity. So inside the onActivityResult(), you can write that code.

Upvotes: -1

Related Questions