Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android, how to detect that the activity is back from another activity?

Tags:

android

For Android, suppose 3 activities, a1 a2 a3, with their click hierarchy, a1->a2->a3.

My questions is in a2, how to detect it is from a3 by pressing the back key, instead of entering from a1?

like image 526
user2718067 Avatar asked Jul 06 '14 14:07

user2718067


People also ask

How do I know if my Android activity is recreated?

You can determine if the activity is finishing by user choice (user chooses to exit by pressing back for example) using isFinishing() in onDestroy . @Override protected void onDestroy() { super. onDestroy(); if (isFinishing()) { // wrap stuff up } else { //It's an orientation change. } }

How do I go back from one Android activity to another?

Android activities are stored in the activity stack. Going back to a previous activity could mean two things. You opened the new activity from another activity with startActivityForResult. In that case you can just call the finishActivity() function from your code and it'll take you back to the previous activity.


1 Answers

You can use onActivityResult to check for return from another activity. Put this code within your a2 activity.

Declare the request code as a constant at the top of your activity:

public static final int OPEN_NEW_ACTIVITY = 123;

Put this where you start the new activity:

Intent intent = new Intent(this, NewActivity.class);
startActivityForResult(intent, OPEN_NEW_ACTIVITY);

Do something when the activity is finished. Documentation suggests that you use resultCode, but depending on the situation, your result can either be RESULT_OK or RESULT_CANCELED when the button is pressed. So I would leave it out.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == OPEN_NEW_ACTIVITY) {
        // Execute your code on back here
        // ....
    }
}

You should take care to run onActivityResult on the Activity itself, and not a Fragment.

You don't actually have to put any code in the a3 activity, but you can send data back if you like.

like image 97
Muz Avatar answered Sep 28 '22 06:09

Muz