0

I have 3 activities. When I go from one activity to another by startActivity, how can I know in the activity I start, what's the activity it's started from?

  • Possible duplicate of [How get name parent activity in child activity](http://stackoverflow.com/questions/9885994/how-get-name-parent-activity-in-child-activity) – George Mulligan Apr 01 '16 at 14:45

2 Answers2

1

Just use intent and specify the parent activity like this :

Activity A will open Activity B

Intent intent = new Intent(this, ActivityB.class);
intent.putExtra("parent_activity", "activityA");
startActivity(intent);

Then in Activity B, check if the bundle contains parent_activity key

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_display_message);

        if (getIntent()!= null && getIntent().getExtras().containsKey("parent_activity")) {
            String parentActivity = getIntent().getStringExtra()("parent_activity");
        }
    }
Mehdi Sakout
  • 773
  • 5
  • 8
0

You can put parent activity's identifier into the intent you're going to start and on the child activity access it.

ParentActivity

static final int ACTIVITY_CODE = 1;
...
Intent intent = new Intent(this, ChildActivity.class);
intent.putExtra(KEY_CODE, ACTIVITY_CODE);
startActivity(intent);
...

ChildActivity

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    int code = getIntent.getIntExtra(KEY_CODE)
    swith(code) {
    //do something
    }
}

We use an integer for key instead of activity name in case you change the name of your activity you'll have less trouble.

How get name parent activity in child activity

Community
  • 1
  • 1
Farshad
  • 3,074
  • 2
  • 30
  • 44