I have a Chat app with this situation:
A - MainActivity
B - Chat activity
C - Forward activity
Let's assume i want to forward a message from Bill to John's chat, i open A -> B -> C, on C i must select the user to forward, so i click on John throwing a new B intent, now in the stack i have A-B-C-B, if from John's chat i press the back button i want to go back in A (MainActivity), but actually i go back in B (Bill's chat), this is a problem because the Chat activity must be only one. For necessity the Chat activity is set as android:launchMode="singleTop" in the manifest, because if i have a Chat in foreground and i click on "new message" android notification, the current Chat is closed and the new one is opened. Reading on developers guide i've found FLAG_ACTIVITY_TASK_ON_HOME, as i can understand with this flag i should be able to back directly from John's chat(B) to MainActivity(A) but doesn't happens.
This is A (MainActivity with sliding tab layout, the Intent is launched from ListFragment Tab activity)
Intent intent = new Intent(getContext(), Chats.class);
Bundle b = new Bundle();
b.putString("nid", list_id.toString());
b.putString("user_id_key", list_user_id.toString());
b.putString("name", list_name.toString());
b.putString("number", list_number.toString());
intent.putExtras(b);
startActivityForResult(intent, 101);
This is B (Chat activity - AppCompatActivity)
Intent intent = new Intent(getApplicationContext(), Forward.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Bundle b = new Bundle();
b.putString("forward_mess", MessText);
b.putString("number", number);
b.putString("conv_id", convId);
intent.putExtras(b);
startActivity(intent);
This is C (Forward activity - AppCompatActivity)
Intent intent = new Intent(getApplicationContext(), Chats.class);
intent.addFlags(Intent.FLAG_ACTIVITY_TASK_ON_HOME);
Bundle b = new Bundle();
b.putString("nid", sel_nid);
b.putString("user_id_key", sel_user_receiver);
b.putString("name", sel_name);
b.putString("number", sel_number);
b.putString("forward_mess", forward_mess);
intent.putExtras(b);
startActivityForResult(intent, 101);
finish();
Also tried with FLAG_ACTIVITY_CLEAR_TOP, but this brings me directly to A->B
Solved using onActivityResult method in Chat activity.
Here the correct activities flow:
MainActivity -> startActivityForResult(chat_intent, 101);
Chat -> startActivityForResult(forward_intent, 5);
Set the onActivityResult method:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//If is 5 means Forward activity was closed
if (requestCode == 5) {
// If 10 means a new Chat was opened, so this one must be closed
if (resultCode == 10) {
finish();
}
}
}
Forward
startActivityForResult(chat_intent, 101);
setResult(10);
finish();