(re)open a specific activity from stack - android

Is there a possibility to reopen a specific activity from the stack?
So say I open activity a, then b, then c. I do not finish a and b while starting new activities. If a push my back-button without overriding it, I would go to B now of course.
But I want to give a button or maybe the back button to open A, or B independent from its location in the stack. This is kind of achievable by finishing the activities (if I would finish b, and press back button from C, I would go to A). But some of my activities I'd rather not finish.
I researched but could not find how to achieve this. Is this possible?
Of course there would be a check needed if the activity is active, and if it is then reopen it or else open it.

You will obviously have to figure out what logic you want to know which Activity to open but this should achieve what you are looking for
#Override
public void onBackPressed()
{
super.onBackPressed();
Intent intent = new Intent(CurrentActivity.this, ActivityYouWant.class);
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
}
Let me know if this isn't what you were looking for.
Flag

the way codeMagic suggested you may produce more Activities in the Activity stack then you need. This may leed to Memory Leaks or other bad behavior.
you should take a look at:
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
or even better finish() your Activities.

Related

How to manipulate current task's Activity back stack?

Currently I have 3 Activity classes A, B and C.
Activity A is a singleTask while other has the default launch mode.
Consider a case: the user is first in A, then starts B, and then starts C.
The back stack now is ABC.
Next, the user starts A again.
The back stack now is A, but what I would like to be achieved is ABCA.
I know not setting Activity A to be singleTask can have a back stack : ABCA.
But I really need the Activity A to be the same instance.
Anyone know how to do this?
You have stipulated two conditions:
what I would like to be achieved is ABCA.
and
I really need the Activity A to be the same instance.
These two conditions are mutually contradictory. Absolutely.
What you want is impossible.
That is all.
Are you sure you need singleTask and not singleTop ? Could you describe why do you need it singleTask ?
That is not possible.
if you want to open existing activity then
launch your activity as
Intent intent = new Intent(this, YourActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);

How will I permanently exit my Android app using onBackPressed from my last Activity

I have 8 Activities in my Android app and I want:
1)Every time I press Back button during my first 7 Activities to go back to my previous Activity(Act1< Act2< Act3< Act4< Act5< Act6< Act7) BUT
2)ONLY when I am in the 8th Activity I want to definitely exit my Android app and go to my phone's Home Screen.I try to do it by overriding onBackPressed method in my 8th Activity (Phone Home Screen<-Act8)
I found an Android implementation in which I insert finish();in every intent of all my 8 Activities but this is not what I want since this way I can't go back to the previous Activity whenever I want(with finish(); every current Activity is removed from back stack).
How will I do it please?
My code so far in my 8th Activity is:
#Override
public void onBackPressed()
{
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
Another way: create a 9th Activity and call it FinishAllActivity or something like that. Make this activity call finish() and then return in its onCreate().
In onBackPressed() in Activity 8, start FinishAllActivity using the FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TASK flags (see this question for more details). Activities 1-8 will be removed from the stack, then the 9th Activity will start and immediately terminate and your task stack is clear. When you reopen the app it should start from Activity 1.
The advantage of doing it this way is that you don't have to modify Activities 1-7.
Add a public static boolean to one of your classes that indicates the app is exiting. Set this boolean in activity 8 when you want the app to finish, and have all of your other activities check it in their onResume() and finish immediately if it is true. Make sure the first activity clears it before finishing, or it may still be set the next time the app runs. (Android doesn't necessarily discard the VM when your last activity finishes, so the class and its static members may be reused next time.)
Note that this is the simple way, not the "Android way." Global variables are generally frowned upon, for reasons you can Google. The "correct" way to do this would be to start each activity for result and return a result to onActivityResult(...) that indicates whether the app is exiting.
You can implement a broadcast receiver and have each of your Activities that you want to close call finish() when they receive the broadcast (which will be sent from your last activity). I would imagine you'd need to have your broadcast receiver class be either an anonymous inner class or a private class within your activity(s) so that you can easily access your enclosing Activity's finish method.
Here's a good example of broadcast receivers:
http://www.tutorialspoint.com/android/android_broadcast_receivers.htm
Look at the custom intents section.
Doing it this way is a loosely coupled way to implement what you are looking to do.
use FLAG_ACTIVITY_CLEAR_TOP Flag in your intent like below example.
Intent intent = new Intent(getApplicationContext(),FirstActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);
in your first activity check below condition.
if (getIntent().getBooleanExtra("EXIT", false)) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
finish();
}
here FLAG_ACTIVITY_CLEAR_TOP work like below example
consider a task consisting of the activities: A, B, C, D. If D calls startActivity() with an Intent that resolves to the component of activity B, then C and D will be finished and B receive the given Intent, resulting in the stack now being: A, B.
so here you have to call D is your last activity and A is your first activity.
This way you are finishing your 8th Activity returning to your 7th Activity and same time you are like emulating a pressing of Home button on a device. When you rerun your app it will appear with 7th Activity on a screen. If you wish to see the 8th Activity in this case then just remove the finish() method. If you wish next time your app to start with 1st Activity then you should finish all the activities from 8 to 2nd but not the 1st. Also you could launch your 1st Activity adding a FLAG NEW_TASK or some other flags.
UPDATE
My advise (for the quick result without changing the workflow) is to use startActivityForResult() to start all activities in chain. When user exits the app just return a special parameter using setActivityResult() to get all nested activities know about user's choice making all nested Activities to run finish(). This way all your 8 activities will be finished properly.

How to remove old activities from backstack? (true way)

I'm new to Android development and here's my problem:
I have 2 activities: A and B.
From A, I call B via startActivity(new Intent(A.this, B.class))
From B, I do some things and return to A the same way: startActivity(new Intent(B.this, A.class))
However, when on new-A I press "Back" button, first I see B class and then the old (unchanged version) of A class.
I've tried placing finish(); inside onPause() method. However, then my Activity crashes on orientation change.
How can I properly control activity backstack? Thanks in advance.
When you call startActivity without any additional flags, you will create a new instance of the Activity specified. This means that your back stack ends up looking like this:
A -> B -> A(2)
You have two options:
First option, you can add flags on the Intent that instructs it to reorder A to the front if it is already present in the back stack. Note that this will not close B; you have to call finish() in B afterward.
Intent intent = new Intent(B.this, A.class);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startAcvitiy(intent);
finish();
Second option is to use startActivityForResult instead of startActivity in A and have Activity B pass a result back to A. I think this is much cleaner and it gives you a very easy way to react to what happened when B was finished (e.g. you can update your UI). See this guide from the Android developers site.
Either StartActivityForResult or think about using fragments. If you need to jump between activities think about why you are doing this? If you are passing info between the two then there are a couple of options. Fragments give you the option and you can hold the data on the Activity that hosts the fragments or you can have a Singleton living in an Application class that you would extend.
Read about activity lifecycle - here. You have to implement saving of instance.
It sounds like that rather than calling startActivity in to go back to A, you can just call instead finish();. This will land you back on your previous Activity.
Alternatively you can accomplish the same if you use FLAG_ACTIVITY_CLEAR_TOP:
Intent intent = new Intent(B.this, A.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
Regarding the accepted answer's suggestion to use FLAG_ACTIVITY_REORDER_TO_FRONT - for your case it really doesn't matter. but in a slightly different case where you have A->B->C and you use REORDER to go back to A, you'd actually end up with a stack that looks like B->C->A. With CLEAR_TOP, you'd end up with just A. Point is, REORDER is meant to REORDER, CLEAR_TOP is supposed to pop the backstack. In your simple case they happen to accomplish the same, but in my opinion it's better practice to use the flags as they're intended.

Android - how to start chain of activities?

I intend to start 3 activities in a chain (like from main open Activities A, B and then C, which will be visible for the user), but I wasn't able to find some way how to do that in Android. Do not ask me why, I just have to do that for restoring my application state, where is was before.
Thanks for any ideas
Waypoint
Edit:
Ok, I have tried opening activities in For cycle, but they aren't opened properly. They are chained, but recreated only when I press back button and they display to me. I need some solution which leads to: open A, if A is opened check if needs to open B -> YES, open B, check if needs to open C -> YES, open C, no need to open another activity -> FINISH
prior to start any activity , decide which activity should be start .
Lets take your case >>first check for B , if yes check for C , now open the required 1 .
i understand comparable data is inside the activities, but a right data structure will always allow you to access the data wherever and whenever it actually requires .
For future readers: if you want to start activity with proper back stack, you should use TaskStackBuilder.
define the natural hierarchy for your activities by adding the android:parentActivityName attribute to each element in your app manifest file
create an instance of TaskStackBuilder and call addNextIntentWithParentStack(), passing it the Intent for the activity you want to start.
For more details see official documentation
Override the onResume-method in each activity. Add the check and the start of the activity there.
public void onResume() {
if( condition )
startActivity( intentForTheNextActivity );
}
Where condition is whatever condition you might have (in your example if B should be started, C should be started etc.) and intentForTheNextActivity is the intent for the following activity in the chain (e.g. if now in A, the intent is for B etc.).
I'm having a very hard time understanding exactly what it is you're trying to do. Sometimes it seems like it's a chain (A opens B, B opens C and so forth) sometimes it seems you want some random flow (A opens B, B opens A, A opens B, B opens C) - which makes it really hard to give you a specific answer.
What I can do, is recommend that you read up on the following:
Activity Lifecycle
Starting Activities and getting results (in particular the methods startActivityForResult and setResult)
If you need more help than this - you need to explain yourself better (maybe with a diagram or some sample code of what you have tried so far).
You didn't provide any information of what you've tried, so i'll give you the simplest answer:
method startActivity(Intent intent), more info here.
Edit: Hmm, how about this? I don't have SDK around me now, but i can provide a concept. I'm not sure if it works, but i hope it'll guide you to soultion.
Let's imagine this is ActivityA's code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (doINeedActivityB) {
Intent activityC = new Intent(this, ActivityC.class);
this.startActivity(activityA);
}
if (doINeedActivityC) {
Intent activityC = new Intent(this, ActivityC.class);
this.startActivity(activityC);
}
}

How do I clear all Activities from the stack?

I am having trouble popping all activities off the stack using Intent.FLAG_ACTIVITY_CLEAR_TOP and android:launchMode="singleInstance".
In my application activity A, launches activity B (via startActivity) which in turn launches activity C (via startActivity). On activity C the user presses a menu item to return to activity A. When they arrive at activity A, I want only A on the stack such that if they click the back button they return to the home screen (desktop).
This is the code that I am currently using when the user presses a button to return to A:
Intent i = new Intent(this, A.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
All activities are defined as android:launchMode="singleInstance" in the project manifest.
My code doesn't seem to work though. Once I'm back on activity A if I click the back button I return to activity C. Am I misunderstanding how to use Intent.FLAG_ACTIVITY_CLEAR_TOP?
I've always found the best way to ensure C would be removed from the stack is to call finish() after startActivity to remove C from the stack.
The documentation does read as though things would behave the way you expected them to, but it would seem this isn't happening, so finish() will ensure C is removed.
I usually use the technique Al suggested (calling finish() after starting the new activity).
You could also experiment with task affinity. I've never done that myself, but it may be relevant in your case as well. See this thread: http://groups.google.com/group/android-developers/browse_frm/thread/ca3b26a14d024597/129e37375105901b

Categories

Resources