I want to finish only certain activities(3. and 4.) and sending data to 2. activity. How can I do that?
You have 2 choices:
1. Use startActivityForResult()
In this case, Activity2
should launch Activity3
using startActivityForResult()
. The result will be returned to Activity2
in a call to onActivityResult()
.
When Activity3
launches Activity4
it should use startActivity()
and should set Intent.FLAG_ACTIVITY_FORWARD_RESULT
in the Intent
and call finish()
.
When Activity4
is ready to return the data, it should call setResult()
with the data and then finish()
. This will return the result to Activity2
.
2. Use FLAG_ACTIVITY_CLEAR_TOP | FLAG_ACTIVITY_SINGLE_TOP
In this case, Activity2
should launch Activity3
using startActivity()
.
Activity3
should launch Activity4
using startActivity()
.
When Activity4
is ready to return the data, it should create an Intent
that contains the data (as "extras") and then do the following:
Intent intent = new Intent(this, Activity2.class);
intent.addFlag(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
finish();
This will cause Activity3
and Activity4
to be removed from the task stack onNewIntent()
will be called on the existing instance of Activity2
. Activity2
should override onNewIntent()
and can retrieve the returned data from the "extras" in the argument passed to onNewIntent()
.