Wednesday, August 10, 2011

Importance of intent flag FLAG_ACTIVITY_REORDER_TO_FRONT in Android?

Today i was studying a lot about Task affinities and Back Stack and trying to understand them clearly as i am running into a situation where i launched an activity two times. Look at this scenario i have a menu with five options say A , B , C , D and E which are different activities meant for different purposes. I launched B activity then A activity then C activity and again A activity and i pressed back key now A activity is finished C is displayed again i pressed back key as per my imagination it should display B activity but i was surprised to see A activity.
B -> A -> C -> A on pressing back key it should be A -> C-> B
It seems that it maintains the back stack without reordering and i came across an useful flag in Intents class FLAG_ACTIVITY_REORDER_TO_FRONT which will solve this kind of issues when intent resolves to the activity in the current task it moves this activity to the top of the stack in this way.
B->A->C->A will be reordered as B->C->A

So the code will be as follows
Intent intent = new Intent();
intent.setClass(...., ....);
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);

Happy coding .....

2 comments:

  1. if suppose if traverse B twice and use FLAG_ACTIVITY_REORDER_TO_FRONT does B goes to first by moving A to next?

    ReplyDelete
  2. Yes it goes to front.Usually this help is helpful when from a menu you are traversing some activity many times it keeps only one copy on the stack

    ReplyDelete