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

You can use following methods

onCreate() when activity is first created ( from a1 to a2). This method won't be called when you come back via pressing back button.

onRestart() activity was in background and comes to foreground (back press in a3)


onCreate wont get called in case of back press.

There are multiple ways you can infer if you have arrived at this activity by back key press.

  1. Set a boolean in oncreate that says on onCreate is called.

  2. Start C activity by calling startActivityForResult and when you return from C onActivityResult will get called.


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.


Put some key in intent when you start your activity.

   Intent intent = new Intent(getBaseContext(), A1Activity.class);
   intent.putExtra("I_CAME_FROM", "a1");
   startActivity(intent)

And read it in opened activity:

   String flag = intent.getStringExtra("I_CAME_FROM");
   if(flag.equlas("a1")){
   //you came from a1 activity
   }

This will allow you to understand where you came from.

Tags:

Android