How to properly remove all activity stack? - android

Activity A -> Activity B -> Activity C -> Activity D. Pressing back in Activity D should navigate user out of the application, whereas Back should work normally for Activity C, B and A. i.e. C -> back -> B -> back A -> back -> exit.
I tried settings flags with Activity.FLAG_ACITIVITY_CLEAR_TOP, etc.. with different combination. Nothing seems to work. Minimum API level 7.

For #1 Pressing back in Activity D should navigate user out of the application
In ActivityD, you can override onBackPressed or onKeyDown method and then start ActivityA with flag FLAG_ACTIVITY_CLEAR_TOP with an Exit flag(via putExtra method). In ActivityA, you can get that Exit flag value and call finish() if Exit flag is set true.
In Activity A's onCreate method you will have to do is
if (getIntent().getBooleanExtra("EXIT", false)) {
finish();
}
In ActivityD's onBackPressed or onKeyPressed method,
intent = (this, ActivityA.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);
For #2 Exit from ActivityA
You can simply call finish() method on onBackPressed or onKeyPressed.

Have you tried overriding the functionality of the BACK button in Activity D? I'm quite sure this is very related to what you need: Override back button to act like home button
Understand the Android activity life cycle, too.

"Pressing back in Activity D should navigate user out of the application"
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(true);
return true;
}
return super.onKeyDown(keyCode, event);
}
That's the normal behavior of OS, you don't have to do anything special for it.

Android activities are stored in the activity stack. Going back to a previous activity could mean two things.
You opened the new activity from another activity with startActivityForResult. In that case you can just call the finishActivity() function from your code and it'll take you back to the previous activity.
Keep track of the activity stack. Whenever you start a new activity with an intent you can specify an intent flag like FLAG_ACTIVITY_REORDER_TO_FRONT or FLAG_ACTIVITY_PREVIOUS_IS_TOP. You can use this to shuffle between the activities in your application. Haven't used them much though. Have a look at the flags here

Related

No extras in Activity.getIntent() when going back to it from a child Activity

I have an Activity A which I launch with some extras(i.e. put some data to the Intent that starts the Activity). From this Activity I launch another Activity B. The problem is that when I get back from B to A, by calling finish(), A Activity's getIntent() method returns an Intent that contains no extras.
So, my questions is: Is this normal behavior? And is there some way that I can signal Activity A that I want it to keep the Intent it was started with.
Oh, and please note that I've overridden the onSaveInstanceState() in Activity A.
EDIT:
I'm no longer experiencing this behavior on my device. And I haven't changed anything in the code. I'm using a 3 year old device for testing. I wonder if this might have been caused by a glitch on the device?
I got it figured out. This issue only happens when I click on ActionBar's back arrow and not when I press the device's Back button. Because when Back button is pressed B Activity's finish() method is called and the app normally returns to the already created instance of Activity A, when ActionBar's back arrow is clicked by default the Activity B doesn't call the finish() method, instead it creates a new instance of the Activity A due to the Android lateral navigation functionality. So the solution was to Override the ActionBar's back arrow click functionality like this(method added to Activity B):
#Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
int itemId = menuItem.getItemId();
if (itemId == android.R.id.home) {
onBackPressed();
return true;
}
return super.onOptionsItemSelected(menuItem);
}
Is this normal behavior?
yes it is. Start B with startActivityForResult , and in A, override onActivityResult. Before finishing B call setResult(int, intent), filling up the intent with the data you want to return to A. onActivityResult get the same intent, as third parameter.
Yes The Behavior is Normal. If You want to start an Activity X from an Activity Y and get some data from X and return to Y then you have to use startActivityForResult(intent,request_code)
Then you need to override theonActivityResult()` method
In the Activity X after creating the intent and putting the data in the intent you need to do the following
setResult(RESUKT_OK,i);
`

Activity Flows A->B->C->A in android

Suppose I have 3 activities: A, B and C.
A: Home Activity
B: Information gather Activity
C: Information display Activity
My desired flow goes like:
A triggers B to gather information.
When B ends, C will get the information and display.
A->B->C->A.
When C ends, it should go back to A. (this is never a problem as I will B: finish())
My first attempt: (Failed due to I do not want to see the A after B, even for few miliseconds)
A triggers B to gather information. (startActivityAsResult)
B pass result to A, and B :finish(). (onActivityResult)
Then A triggers C to display. (startActivity)
My second attempt: (Succeed but I'm thinking is there a better way despite this?)
A triggers B to gather information. (startActivity)
B triggers C, and B :finish(). (startActivity)
Questions:
Is there any alternative way (which is simpler/direct) of defining the sequence of navigation flows like i see taskBuilder with nextIntent() API?
In Activity C on back button press clear the backstack and navigate to A
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
onBackPressed();
}
return super.onKeyDown(keyCode, event);
}
public void onBackPressed() {
Intent myIntent = new Intent(C.this,A.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);// clear the backstack
startActivity(myIntent);
finish();
return;
}
A to B To C
In your activity back stack you will have C at the top, next B and next A.
When you press back button in C, activity C is popped from stack, destroyed and the previous activity B takes focus. So if you wish to navigate to A from C ,clear the back stack , navigate to A and finish the current activity.
If I understand you correctly, you just want to make it impossible for the user to use the back button to get into activities that have already been "used up," yes? Try modifying the activity tags in your AndroidManifest.xml using something like the following:
<activity
android:name="yourpackagename.yourappname.YourActivity"
android:label="#string/your_app_title"
android:noHistory="true" >
Once you add the noHistory attribute, the activity in question is yanked from the activity history, and you'll be able to force your user to go only forwards as your intents describe.

How to close activity and go back to previous activity in android

I have a main activity, that when I click on a button, starts a new activity, i used the following code to do so:
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
The above code was run from the main activity.
Now in my new activity which is called by the main activity, I have a back button.
When I click on this back button I want my new activity to close and it must go back to the original main activity.
I have tried calling super.finish() and just finish() (from the new activity) but this then closes my entire application (including my main activity).
How can I just close the activity that is currently in focus, and then return to the main activity?
EDITED
The fact that my phone's back button also closes my entire app, leads me to think that i have started up the second activity incorrectly?
OK I have been looking,
I created a Settings Activity that uses the same manifest code and the same code to Start the activity.
For the settings Activity when I push the back button, it returns to the Main activity.
With the activity mentioned above in the main question it simply exits my entire app.
So the problem doesn't seem to be with the code to finish the activity but the activity itself.
I think you are calling finish() method in MainActivity before starting SettingsActivity.
The scenario which you have described will occur in following two ways:
EITHER
You have set android:noHistory = "true" for MainActivity inside AndroidManifest.xml which causes MainActivity to finish automatically on pressing the back key.
OR
Before switching to your 'SettingsActivity', you have called finish() in your MainActivity, which kills it. When you press back button,since no other activity is preset in stack to pop, it goes back to main screen.
You can go back to the previous activity by just calling finish() in the activity you are on. Note any code after the finish() call will be run - you can just do a return after calling finish() to fix this.
If you want to return results to activity one then when starting activity two you need:
startActivityForResults(myIntent, MY_REQUEST_CODE);
Inside your called activity you can then get the Intent from the onCreate() parameter or used
getIntent();
To set return a result to activity one then in activity two do
setResult(Activity.RESULT_OK, MyIntentToReturn);
If you have no intent to return then just say
setResult(Activity.RESULT_OK);
If the the activity has bad results you can use Activity.RESULT_CANCELED (this is used by default). Then in activity one you do
onActivityResult(int requestCode, int resultCode, Intent data) {
// Handle the logic for the requestCode, resultCode and data returned...
}
To finish activity two use the same methods with finish() as described above with your results already set.
if you use fragment u should use
getActivity().onBackPressed();
if you use single activity u can use
finish();
When you click your button you can have it call:
super.onBackPressed();
Button edit = (Button) view.findViewById(R.id.yourButton);
edit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(this, YourMainActivity.class);
startActivity(intent);
finish();
}
});
try this code instead of finish:
onBackPressed();
I believe your second activity is probably not linked to your main activity as a child activity. Check your AndroidManifest.xml file and see if the <activity> entry for your child activity includes a android:parentActivityName attribute. It should look something like this:
<?xml ...?>
...
<activity
android:name=".MainActivity"
...>
</activity>
<activity
android:name=".ChildActivity"
android:parentActivityName=".MainActivity"
...>
</activity>
...
This closes the entire application:
this.finish();
You are making this too hard. If I understand what you are trying to do correctly, the built-in 'back' button and Android itself will do all the work for you: http://developer.android.com/guide/components/tasks-and-back-stack.html
Also, implementing a custom "back" button violates Core App Quality Guideline UX-N1: http://developer.android.com/distribute/googleplay/quality/core.html
I don't know if this is even usefull or not but I was strugling with the same problem and I found a pretty easy way, with only a global boolean variable and onResume() action. In my case, my Activity C if clicked in a specific button it should trigger the finish() of Activity B!
Activity_A -> Activity_B -> Activity_C
Activity_A (opens normally Activity_B)
Activity_B (on some button click opens Activity_C):
// Global:
boolean its_detail = false;
// -------
SharedPreferences prefs = getApplicationContext().getSharedPreferences("sharedpreferences", 0);
boolean v = prefs.getBoolean("select_client", false);
its_detail = v;
startActivity(C);
#Override
public void onResume(){
super.onResume();
if(its_detail == true){
finish();
}
}
So, whenever I click the button on Activity C it would do the "onResume()" function of Activity B and go back to Activity A.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if ( id == android.R.id.home ) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
Try this it works both on toolbar back button as hardware back button.
Finish closes the whole application, this is is something i hate in Android development not finish that is fine but that they do not keep up wit ok syntax they have
startActivity(intent)
Why not
closeActivity(intent)
?
We encountered a very similar situation.
Activity 1 (Opening) -> Activity 2 (Preview) -> Activity 3 (Detail)
Incorrect "on back press" Response
Device back press on Activity 3 will also close Activity 2.
I have checked all answers posted above and none of them worked. Java syntax for transition between Activity 2 and Activity 3 was reviewed to be correct.
Fresh from coding on calling out a 3rd party app. by an Activity. We decided to investigate the configuration angle - eventually enabling us to identify the root cause of the problem.
Scope: Configuration of Activity 2 (caller).
Root Cause:
android:launchMode="singleInstance"
Solution:
android:launchMode="singleTask"
Apparently on this "on back press" issue singleInstance considers invoked Activities in one instance with the calling Activity, whereas singleTask will allow for invoked Activities having their own identity enough for the intended on back press to function to work as it should to.
on onCreate method of your activity
write the following code.
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
Then override the onOptionsItem selected method of your activity as follows
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
finish();
}
return super.onOptionsItemSelected(item);
}
And you are good to go.
Just don't call finish() on your MainActivity then this eliminates the need to Override your onBackPressed() in your SecondActivity unless you are doing other things in that function. If you feel the "need" for this back button then you can simply call finish() on the SecondActivity and that will take you to your MainActivity as long as you haven't called finish() on it
it may be possible you are calling finish(); in the click button event so the main activity is closed just after you clicking the button and when you are coming back from next activity the application is exit because main activity is already closed and there is no active activity.
You have to use this in your MainActivity
Intent intent = new Intent(context , yourActivity);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
context.startActivity(intent);
The flag will start multiple tasks that will keep your MainActivity, when you call finish it will kill the other activity and get you back to the MainActivity
In case none of the above answers helped, I think this might help someone.
I was also having the same problem while pressing the built-in back button or my custom back button, the app closes without returning to the previous activity.
I was calling the second activity from the first activity's toolbar.
But in the starter activity I was calling this:
case android.R.id.home:
if (isActionMode) {
clearSelectingToolbar();
adapter.notifyDataSetChanged();
} else {
onBackPressed(); // This was making the activity to finish
}
break;
And this code to start the activity
case R.id.settings:
context.startActivity(new Intent(ShowAllDirectoriesActivity.this, SettingsActivity.class));
After removing 'case android.R.id.home' part, my activity was able to perform in a normal flow i.e getting back to the previous activity.
So check it if you are also using the same thing!
{ getApplicationContext.finish(); }
Try this method..

How to destroy an Activity so it doesn't show up when the back button is pressed?

I have two Activities, A and B. Here is a normal scenario: A is running, then sends an intent to B. A is paused, and B displays. When the user presses the back button from B, B us destroyed and the user is returned to A.
However, there is a case where B needs to re-create itself. To do this, I call finish() and then startActivity() on B and that works fine. But then, when I click the back button, it shows B again, and so I need to click the back button once more to get back to A.
How can I re-start B, but still be able to press the back button only once to return to A?
The following will dispose of the current activity while launching the next intent:
Intent launchNext = new Intent(getApplicationContext(), NextActivity.class);
launchNext.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(launchNext);
To override the back button, use the following:
#Override
public void onBackPressed() {
super.onBackPressed();
this.finish(); // or do something else
}
This can be solved by taking a closer look at your intent flags. Check out http://developer.android.com/reference/android/content/Intent.html and they give more information about what lifecycle you are shooting for.
Also, don't forget that you can override the back button functionality.
This may be helpful in case you want to manage your life cycle more closely.
For example, you can also make sure to go back to A if back from B. And close your app if back on A.

How to prevent going back to the previous activity?

When the BACK button is pressed on the phone, I want to prevent a specific activity from returning to its previous one.
Specifically, I have login and sign up screens, both start a new activity called HomeScreen when successful login/signup occurs. Once HomeScreen is started, I want to prevent the users from being able to return to the login or sign up screens by pressing the BACK key.
I tried using Intent.FLAG_ACTIVITY_NO_HISTORY, but since the application has Facebook integration, when the 'Login with Facebook' is used, Facebook should return to the initial login screen, therefore I should keep a history of these activities.
I thought of overriding the behaviour of the BACK button on HomeScreen to directly finish an application when the button is pressed and I used
#Override
public void onBackPressed() {
finish();
}
but that also does not work.
My suggestion would be to finish the activity that you don't want the users to go back to. For instance, in your sign in activity, right after you call startActivity, call finish(). When the users hit the back button, they will not be able to go to the sign in activity because it has been killed off the stack.
Following solution can be pretty useful in the usual login / main activity scenario or implementing a blocking screen.
To minimize the app rather than going back to previous activity, you can override onBackPressed() like this:
#Override
public void onBackPressed() {
moveTaskToBack(true);
}
moveTaskToBack(boolean nonRoot) leaves your back stack as it is, just puts your task (all activities) in background. Same as if user pressed Home button.
Parameter boolean nonRoot - If false then this only works if the activity is the root of a task; if true it will work for any activity in a task.
I'm not sure exactly what you want, but it sounds like it should be possible, and it also sounds like you're already on the right track.
Here are a few links that might help:
Disable back button in android
MyActivity.java =>
#Override
public void onBackPressed() {
return;
}
How can I disable 'go back' to some activity?
AndroidManifest.xml =>
<activity android:name=".SplashActivity" android:noHistory="true"/>
There are two solutions for your case, activity A starts activity B, but you do not want to back to activity A in activity B.
1. Removed previous activity A from back stack.
Intent intent = new Intent(activityA.this, activityB.class);
startActivity(intent);
finish(); // Destroy activity A and not exist in Back stack
2. Disabled go back button action in activity B.
There are two ways to prevent go back event as below,
1) Recommend approach
#Override
public void onBackPressed() {
}
2)Override onKeyDown method
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode==KeyEvent.KEYCODE_BACK) {
return false;
}
return super.onKeyDown(keyCode, event);
}
Hope that it is useful, but still depends on your situations.
Since there are already many great solutions suggested, ill try to give a more dipictive explanation.
How to skip going back to the previous activity?
Remove the previous Activity from Backstack. Simple
How to remove the previous Activity from Backstack?
Call finish() method
The Normal Flow:
All the activities are stored in a Stack known as Backstack.
When you start a new Activity(startActivity(...)) then the new Activity is pushed to top of the stack and when you press back button the Activity is popped from the stack.
One key point to note is that when the back button is pressed then finish(); method is called internally. This is the default behavior of onBackPressed() method.
So if you want to skip Activity B?
ie A<--- C
Just add finish(); method after your startActvity(...) in the Activity B
Intent i = new Intent(this, C.class);
startActivity(i);
finish();
finish() gives you method to close current Activity not whole application. And you better don't try to look for methods to kill application. Little advice.
Have you tried conjunction of Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS | Intent.FLAG_ACTIVITY_NO_HISTORY? Remember to use this flags in Intent starting activity!
Put finish() just after
Intent i = new Intent(Summary1.this,MainActivity.class);
startActivity(i);
finish();
If you don't want to go back to all the activities on your application, you can use
android:launchMode="singleTask"
Learn more here: http://developer.android.com/guide/topics/manifest/activity-element.html
paulsm4's answer is the correct one. If in onBackPressed() you just return, it will disable the back button. However, I think a better approach given your use case is to flip the activity logic, i.e. make your home activity the main one, check if the user is signed in there, if not, start the sign in activity. The reason is that if you override the back button in your main activity, most users will be confused when they press back and your app does nothing.
This method is working fine
Intent intent = new Intent(Profile.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
#Override
public void onBackPressed() {
}
When you create onBackPressed() just remove super.onBackPressed();and that should work
Just override the onKeyDown method and check if the back button was pressed.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_BACK)
{
//Back buttons was pressed, do whatever logic you want
}
return false;
}
Put
finish();
immediately after
ActivityStart
to stop the activity preventing any way of going back to it.
Then add
onCreate(){
getActionBar().setDisplayHomeAsUpEnabled(false);
...
}
to the activity you are starting.
AndroidManifest.xml
<activity
android:name=".welcome.SplashActivity"
android:noHistory="true" // just add this line
android:exported="true">
</activity>

Categories

Resources