Android get previous activity

2019-01-08 20:09发布

问题:

I have 2 activities: Activity1 and Activity2. In each of this activities there is a button that leads me to a third activity (MainActivity). In MainActivity I want to know from which activity page was called.

回答1:

You can use the putExtra attribute of the Intent to pass the name of the Activity.

Calling Activity,

Intent intent = new Intent(this, Next.class);
intent.putExtra("activity","first");
startActivity(intent);

Next Activity,

Intent intent = getIntent();
String activity = intent.getStringExtra("activity");

Now in the string activity you will get the name from which Activity it has came.



回答2:

You can use:

public ComponentName getCallingActivity()

to know which Activity called your current Activity.



回答3:

Use putExtra() to identify the previous activity.

Intent i = new Intent(Activity1.this, MainActivity.class).putExtra("from", "activity1");
startActivity(i);

To check the activity in Main Activity,

if(getIntent().getStringExtra("from").equals("activity1")){
//From Activity 1
}else {
// Activity 2
}


回答4:

When you move from one activity to another you can Pass the activity Name as given below

Intent i = new Intent(this, deliveries.class);
i.putExtra("ActivityName", "ActivityOne");
startActivity(i);

and check the activity name in the other activity

Bundle extra = getIntent().getExtras();
String activityName = Long.parseLong(extra.getSerializable("ActivityName")
toString());

I think it can solve your problem



回答5:

when you start your activity :

Intent intent = new Intent(activity, HistoryDetailsResults.class);
 intent.putExtra(Activity.ACTIVITY_SERVICE, activity.getLocalClassName());
 activity.startActivity(intent);

Using Activity.ACTIVITY_SERVICE I assume you use a good practice. (Activity.ACTIVITY_SERVICE is the String : 'activity')

activity.getLocalClassName() give this : view.YourActivity as String

EDIT : Instead of using activity activity.getLocalClassName() I prefer use activity.getClass().getSimpleName()

Step 1 in your start activity

Intent intent = new Intent(activity, HistoryDetailsResults.class);
 intent.putExtra(Activity.ACTIVITY_SERVICE, activity.getClass().getSimpleName());
 activity.startActivity(intent);

Step 2 in your destination activity

Intent intent = getIntent();
String startActivity = intent.getStringExtra(Activity.ACTIVITY_SERVICE)
String activityToCompare = YourActivityToCompare.class.getSimpleName()

And what you want to do :

if( startActivity.equalsIgnoreCase(activityToCompare) {
    //Do what you want
}