Reputation: 15525
If I have activities like following path,
A --> B --> C --> D
Currently I am in Activity D. So If I want to go back directly to B, then how it is possible?
I done the following way.
List<Activity> activities = new ArrayList<>();
This list will have the all loaded activities, which means activities added to this list on onCreate()
method.
So currently this list will have A, B, C, D
, So if want to go back directly to B
then what I will do is get the last two activities from this list and finish it by using finish()
. I know this is not the proper way.
So I want to know, whether there is any better way to do this or not?.
Note : At some cases only I will go to Activity B directly, So I can't finish C while start Activity D.
Update
Also I can go back to Activity A directly from Activity D, So my question is
I can skip any activity at any time and also go back to any activity at any time
is it possible?
Upvotes: 0
Views: 123
Reputation: 147
Use the onBackPressed method on your D Actvity like this.
@Override
public void onBackPressed() {
super.onBackPressed();
Intent i = new Intent(D.this, B.class);
startActivity(i);
}
Upvotes: 0
Reputation: 328
you can implement separate OnBackPressed() Method for each activity and move to any activity you want, but if you want to save the instance of the current activity also you need to use StartActivityForResult() method.
Upvotes: 0
Reputation: 530
I think You should use IntentFlag to clear all previous activty. you must read this tutorials for more clearfication.
Main Reference : http://developer.android.com/guide/components/tasks-and-back-stack.html
Source : http://tips.androidhive.info/2013/10/how-to-clear-all-activity-stack-in-android/
Intent i = new Intent(D.this, B.class);
// set the new task and clear flags
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
Upvotes: 0
Reputation: 1128
You should probably use startActivityForResult when starting Activity D from Activity C.
Whenever you want to finish Activity C, make sure you do setResult(RESULT_OK) in Activity D when you're about to finish it.
And in Activity C, override onActivityResult and do the following:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != RESULT_OK)
return;
if (requestCode == REQUEST_CODE_SHOULD_FINISH_ACTIVITY) {
//add any other code you might wanna add
finish();
}
}
Upvotes: 2