How to kill all my application's activities? - android

How can I kill all the Activities of my application?
I tried using this.finish() but it just kills one Activity.
In fact, I would like when the user touches the back button (in only one of the activities), the application to do the same as if he pressed the Home button.

You can set android:noHistory="true" for all your activities at AndroidManifest.xml. Hence they will not place themselves onto history stack and back button will bring you to the home screen.

This has been discussed many times before. Essentially there's no easy way, and there's not supposed to be. Users press Home to quit your app (as you have pointed out).

Override the onBackPressed method, and do what happens when they press the home button. It's not really closing all the activities but what you're asking is that the back press in a certain activity emulates the home button.
#Override
public void onBackPressed() {
Intent i = new Intent(Intent.ACTION_MAIN);
i.addCategory(Intent.CATEGORY_HOME);
startActivity(i);
}
Placing that in an activity will go home when you press back. Note that the original implementation of the onBackPressed method includes a call to super, it's removed on purpose. I know this question is super old, but he's explicitly asking something else

To kill all the activities, use these code on onBackPressed.
#Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount()>0) {
getFragmentManager().popBackStackImmediate();
} else {
finishAffinity();
System.exit(0);
}
}

Related

How to clear activity stack trace on back press event?

I have created an application that has multiple pages and navigation from one to another represents a crucial flow. I don't want the user to be able to press the back button and escape the activity without first warning him and then finally deleting all stack trace such that when the activity is launched again it starts afresh.
As of yet I have been using something similar to the function below :
#Override
public void onBackPressed()
{
this.finish();
Intent int1= new Intent(this, Home.class);
int1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(int1);
super.onBackPressed();
}
But sometimes when after quitting the application when I launch it again it restarts from some random page or the one from where I quit the application (basically not the home screen from where it is expected to start)
I cannot think of a cleaner way to quit the application other than clearing all the previous activity flags as described in the code.
Any help on the above is appreciated!
EDIT :
Anytime during the flow of my activity if the user presses the back button, I want the control to be thrown back to the main page (clearing all the previous activity stack traces). Such that in case someone re-lanches the application it will re start normally from the main page.
You don't need any of this custom code in onBackPressed(). All you need to do is add this to all of your <activity> definitions in the manifest (except the root activity):
android:noHistory="true"
This ensures that none of your activities (expect the root activity) is recorded in the back stack. When the user clicks the BACK key, it will just return to the root activity.
Another benefit of this is that if the user leaves your app (by clicking HOME or by pulling down the notification bar and clicking on a notification, when he returns to your app it will also just return to your root activity.
Anytime during the flow of my activity if the user presses the back
button, I want the control to be thrown back to the main page
(clearing all the previous activity stack traces).
This can be done just by finishing all the activities as they move forward, except the MainActivity.
Such that in case someone re-lanches the application it will re start
normally from the main page.
Is it like if user is in Activity_5 and uses Home Button and relaunches the app again, MainActicity must appear?
IF so, you can call finish() in onPause() of every Activity except MainActivity
EDIT:
Might not be the perfect solution, but this is what I did to achieve exactly the same(logout in my application):
OnBackPressed() in any activity updates a boolean shared preference say backPressed to true and in onResume() of all the Activities, except MainActivity check its value and finish if true.
#Override
protected void onResume() {
super.onResume();
SharedPreferences mSP = getSharedPreferences(
"your_preferences", 0);
if (mSP .getBoolean("backPressed", false)) {
finish();
}
}
Back Button is used to go back to the previous activity. So i would not override the back button to clear activity stack. I suggest you use a Action Bar for this purpose. Navigate to Home Screen of the application using the application icon.
http://developer.android.com/guide/topics/ui/actionbar.html
Also check this link and comments below the answer by warrenfaith
android - onBackPressed() not working for me
#Override
public void onBackPressed()
{
moveTaskToBack(true);
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
}
you can use that code, it's work for me!

Android activity flow & navigation up/back

I'm working on an Android application that has 4 activities :
A -> B -> C -> D
When I'm going from A to B, from B to C, or from C to D, I put some extras in the Intent.
I guess navigation for something like that is quite simple: there's no need to redefine the back button, and for the "up" action bar button, a simple "finish()" would be to correct way to do it (?)
Now, the problem is that from A, I can also go directly to D. Still no need to redefine the back button, it will go back to A, and that's what I want, but for the "up" button, it must go to C, and from C, up will lead to B, ...
What is the correct way to do that?
Thanks for your answers
To control the flow between the various activities explicitly, I call finish() in each activity when I respond to user input by starting a new activity:
startActivity(intentForNewActivity);
finish();
That leads to that instance of the orignal Activity being destroyed. In each activity I create an Intent to start up the activity I want to go back to. Then write:
#Override public void onBackPressed() {
startActivity(intentWhereIWantToGoNext);
finish();
}
I originally wrote here that I called finish() in onStop(), which does work while the app remains running, but does not give the desired result if the app is stopped for any reason. Sorry for the confusion, and thanks to PravinCG, who, while his comments were not entirely on the right track, at least made me think more carefully.
One of the way is to actually have the same stack but use extras to perform the toggle.
For Instance: When you want to go from A -> D
go from A->B->C->D and use intents to handle whether you want to simply bypass activity or display it. Same is the case in reverse order user resultIntent for that.
Place the following code before the last bracket.
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}

Android: Activity A -> C, but C -> B -> A via back button, how to do that?

I have three activities: A, B, C.
Activity A can start B or C.
When A starts C i can return to A just have pressed back button. But i want "return" to B and then to A (with second press of back button).
I tried to use TaskBackStack in this way:
final TaskStackBuilder builder = TaskStackBuilder.create(this)
.addParentStack(this)
.addNextIntent(new Intent(this, B.class))
.addNextIntent(new Intent(this, C.class));
builder.startActivities();
But its not working... Can anyone help me?
Sorry for my English and thanks in advance
Override onBackPressed method in your activity C.
#Override
public void onBackPressed() {
super.onBackPressed();
//finish();
Intent intent = new Intent(ActivityC.this,ActivityB.class);
startActivity(intent);
}
If you write finish you can go to Activity A because you came from Activity A. That's why use intents. Like that in Activity B also.
#Override
public void onBackPressed() {
super.onBackPressed();
//finish();
Intent intent = new Intent(ActivityB.this,ActivityA.class);
startActivity(intent);
}
Let me know the status?
Override your onKeyDown method
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
//Do stuff, like launching a new activity
return true;
}
return super.onKeyDown(keyCode, event);
}
Before try to answer you question I have some comments about your approach to navigate between your activitys. In general, this approach is not a good idea, because doing that, you are not following the Android Navigation Pattern, and this can make your application not user friendly, since most Android Application use the Navigation Pattern.
The Android Navigation Pattern says:
Temporal navigation, or navigation between historical screens, is deeply rooted in the Android system. All Android users expect the Back button to take them to the previous screen, regardless of other state. The set of historical screens is always rooted at the user's Launcher application (the phone's "home" screen). That is, pressing Back enough times should land you back at the Launcher, after which the Back button will do nothing.
However, there is another possiblite to Navigate in your application using The Android Pattern, but I believe that is not a solution for your problem. You can take a look at Up Navigation
To finalize, I have a relevant comment about solution that uses override the OnBackPressed() to Start a new Activity. You should really avoid that, because using it, you will can make crazy your chronologic navigation. Because when you create an activity inside the OnBackPressed, you are always putting a new activity on Android Stack, so there are two problems here:
The stack can grow quickly depending of the user behavior
Can be hard get out of your applcaiton (Can be very hard to make your stack become empty)
go to this start basic with Activity Lifecycle. you ll have better knowledge of doing this. Go to this Calling one Activity from another in Android. you ll find many examples on google. try it.. one of the example.

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