Activities Stack Issue - java

I have two sets of Activities suppose 3 Activities each set, (A1,B1,C1 || A2,B2,C2) I start my App from A1 then -> B1 -> C1 here I want to jump from C1 to -> A2 and at A2 if I press back it should exist the App and not put me back for C1, then from A2 I navigate to -> B2 -> C2.
So it is basically I want to change the starting Activity, it is like I have two Apps in one App and when I flip to the second App I have to clear the Activity Stack. Is that possible? Any Ideas?

Seems to me you've answered your own question. You wrote:
So it is basically I want to change the starting Activity, it is like
I have two Apps in one App and when I flip to the second App I have to
clear the Activity Stack.
I would do it this way:
Create a DispatcherActivity which is the activity that gets launched when the application is started. This Activity is the root activity of your task and is responsible for launching either A1 or A2 depending... and NOT call finish() on itself (ie: it will be covered by A1 or A2 but still be at the root of the activity stack).
In A1, trap the "back" key and tell the DispatcherActivity to quit like this:
#Override
public void onBackPressed() {
Intent intent = new Intent(this, DispatcherActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addExtra("exit", "true");
startActivity(intent);
}
This will clear the task stack down to the root activity (DispatcherActivity) and then start the DispatcherActivity again with this intent.
In C1, to launch A2, do the following:
Intent intent = new Intent(this, DispatcherActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addExtra("A2", "true");
startActivity(intent);
This will clear the task stack down to the root activity (DispatcherActivity) and then start the DispatcherActivity again with this intent.
In DispatcherActivity, in onCreate() you need to determine what to do based on the extras in the intent, like this:
Intent intent = getIntent();
if (intent.hasExtra("exit")) {
// User wants to exit
finish();
} else if (intent.hasExtra("A2")) {
// User wants to launch A2
Intent a2Intent = new Intent(this, A2.class);
startActivity(a2Intent);
} else {
// Default behaviour is to launch A1
Intent a1Intent = new Intent(this, A1.class);
startActivity(a1Intent);
}
In A2, trap the "back" key and tell the DispatcherActivity to quit using the same override of onBackPressed() as in A1.
Note: I just typed this code in, so I've not compiled it and it may not be perfect. Your mileage may vary ;-)

You can check when the button that is pressed in Activity A2 and then if its a Back button you can close the app. You can use the following method in A2
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
this.finish();
}
return super.onKeyDown(keyCode, event);
}

try launching the activity A2 with this intent - intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

Handle this using onBackPressed and finish methods.
Before launching other activity, better you close the current activity using finish() method.
If you want to go to previous activity on back press, override onBackPressed method and call the particular intent.
In A2 activity, add finish method in onBackPressed method (dont call previous activity here). This is one of the way.

while passing Intent from Activity C1 to A2 use as
Intent intent=new Intent(C1.this,A2.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
and in Your Activity A2 Override Back Button by
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
A2.this.finish();
}
return super.onKeyDown(keyCode, event);
}

if you want to close your app when press the back button instead of go back last activity, you should overwrite the back button. in the overwrite method call finish() method after close the activity. i hope this may help you.
edited:
check the below link : this is for close all activities in your view stack. before closing your app close all activities.
http://www.coderzheaven.com/2011/08/27/how-to-close-all-activities-in-your-view-stack-in-android/

FLAG_ACTIVITY_CLEAR_TOP is not what you are looking for.
i think you are looking for:
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);

Related

How to exit an app when Back Button is pressed

This is a small question but I'm finding very hard to solve this. I have multiple activities. For example A B and C. When app is launched A is opened and on click of button will redirect me to activity B and then from B on click of another button will take me to C. On Back pressed will now bring me back to B and again on Back button is pressed will take me to A which is main Activity.
Now if I press back button, instead the app should exit...it creates loop between B and A and never exit the app.
I already used the following method
Method 1:
use of this.finishonBackPressed which didn't help
Method 2:
use android:nohistory = true in manifest
But If I do so then from C activity it will directly take me to A which I don't want.
Method 2.
Use of
Intent intent = new Intent(Intent.ACTION_MAIN);
//to clear all old opened activities
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
when I use this then everytime this opens up in my device
Please anyone help.
This is my code in Mainactivity now
#Override
public void onBackPressed() {
finish();
super.onBackPressed();
}
But also it don't work and it creates loop between A and B Activity.
Your code (in MainActivity) is incorrect , put finish() after super.onBackPressed()
it must be :
#Override
public void onBackPressed() {
super.onBackPressed();
finishAffinity(); // or finish();
}

Have to press the back button twice to get to previous activity?

I am simply trying to click back and navigate to my previous activity. My flow is this: I go to news_feed activity -> Comments activity -> User Profile activity -> click back (Go to Comments activity) -> click back (This does nothing for some reason) -> Click back (Go back to news_feed activity). I'm not sure why I have to click back twice when I try to go from Comments activity back to news_feed activity. If I go from news_feed activity -> Comments -> press back (Go to news_feed activity) this works perfectly. Here is my code:
news_feed.java:
#Override
public void onBackPressed() {
super.onBackPressed();
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
}
Comments.java:
#Override
public void onBackPressed() {
super.onBackPressed();
this.finish();
}
UserProfile.java:
#Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent(UserProfile.this, Comments.class);
Bundle bundle = new Bundle();
bundle.putString("postId", postId);
bundle.putString("posterUserId", posterUserId);
bundle.putString("posterName", posterName);
bundle.putString("postStatus", postStatus);
bundle.putString("postTimeStamp", postTimeStamp);
bundle.putString("postTitle", postTitle);
intent.putExtras(bundle);
startActivity(intent);
finish();
}
I don't think navigating to these activities would change anything, but I can include the intents that I used to navigate to these activities also if necessary. Otherwise I just included the onBackPressed code that I had for these activities. Any ideas why this might cause a problem? Any help would be appreciated. Thanks.
In your UserProfile class, in onBackPressed() method, you are starting the Comments class again. Why do you have to do this?
What is happening is, you are starting a new Comments activity onBackPressed() of the USerProfile class, so there are two instances of Comments Activity. So you feel you are pressing back btn twice.
If you have to pass data back to Comments from UserProfile class, then make use of setResult() method.
This will be of help
How to pass data from 2nd activity to 1st activity when pressed back? - android
Sending data back to the Main Activity in android
I you want to send back the result to previous activity the start activity by using
startActivityForResult()
insead of
startActivity()
and don't override
onBackPressed()
You can try something like this:
private boolean clicked;
#Override
public void onBackPressed() {
if (!clicked) { // if it was not clicked before, change the value of clicked to true and do nothing directly return, if clicked again, then it will be finish the activity.
clicked=true;
return;
}
super.onBackPressed();
}
And if you are going to use the time, then you can do like this:
private long lastClicked;
#Override
public void onBackPressed() {
if (System.currentTimeMillis() - lastClicked < 1000) { // within one second
super.onBackPressed();
}
lastClicked = System.currentTimeMillis();
}
You don't need to override onBackPressed() if all you're going to do is call startActivity() and finish() in the current activity. The Android backstack will handle both of those for you. Moreover, in your UserProfile.java you are passing data to previous activity. For this, you should use startActvityForResult() in the Comments activity (i.e the previous activity) instead of startActivity().
To learn more about startActvityForResult() visit: https://developer.android.com/training/basics/intents/result.html
public void onBackPressed() {
if (this.lastBackPressTime < System.currentTimeMillis() - 2000) {
this.lastBackPressTime = System.currentTimeMillis();
} else {
//super.onBackPressed(); for exit
//INTENT HERE TO YOUR SECOND ACTIVITY like below
Intent intent=new Intent(A.this,B.class);
startActivirty(intent);
}
}
Create a global variable
private long lastBackPressTime = 0;
Hope this will help you,Let me know..

On physical back button pressed how to go to device's home screen? [duplicate]

When a user presses the back button on an intent, the application should quit. How can I ensure the application quits when the back button is pressed?
In my Home Activity I override the "onBackPressed" to:
#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);
}
so if the user is in the home activity and press back, he goes to the home screen.
I took the code from Going to home screen Programmatically
Immediately after you start a new activity, using startActivity, make sure you call finish() so that the current activity is not stacked behind the new one.
EDIT
With regards to your comment:
What you're suggesting is not particularly how the android app flow usually works, and how the users expect it to work. What you can do if you really want to, is to make sure that every startActivity leading up to that activity, is a startActivityForResult and has an onActivityResult listener that checks for an exit code, and bubbles that back. You can read more about that here. Basically, use setResult before finishing an activity, to set an exit code of your choice, and if your parent activity receives that exit code, you set it in that activity, and finish that one, etc...
A better user experience:
/**
* Back button listener.
* Will close the application if the back button pressed twice.
*/
#Override
public void onBackPressed()
{
if(backButtonCount >= 1)
{
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
else
{
Toast.makeText(this, "Press the back button once again to close the application.", Toast.LENGTH_SHORT).show();
backButtonCount++;
}
}
The app will only exit if there are no activities in the back stack. SO add this line in your manifest android:noHistory="true" to all the activities that you dont want to be back stacked.And then to close the app call the finish() in the OnBackPressed
<activity android:name=".activities.DemoActivity"
android:screenOrientation="portrait"
**android:noHistory="true"**
/>
Why wouldn't the user just hit the home button? Then they can exit your app from any of your activities, not just a specific one.
If you are worried about your application continuing to do something in the background. Make sure to stop it in the relevant onPause and onStop commands (which will get triggered when the user presses Home).
If your issue is that you want the next time the user clicks on your app for it to start back at the beginning, I recommend putting some kind of menu item or UI button on the screen that takes the user back to the starting activity of your app. Like the twitter bird in the official twitter app, etc.
Use onBackPressedmethod
#Override
public void onBackPressed() {
finish();
super.onBackPressed();
}
This will solve your issue.
First of all, Android does not recommend you to do that within the back button, but rather using the lifecycle methods provided. The back button should not destroy the Activity.
Activities are being added to the stack, accessible from the Overview (square button since they introduced the Material design in 5.0) when the back button is pressed on the last remaining Activity from the UI stack. If the user wants to close down your app, they should swipe it off (close it) from the Overview menu.
Your app is responsible to stop any background tasks and jobs you don't want to run, on onPause(), onStop() and onDestroy() lifecycle methods. Please read more about the lifecycles and their proper implementation here: http://developer.android.com/training/basics/activity-lifecycle/stopping.html
But to answer your question, you can do hacks to implement the exact behaviour you want, but as I said, it is not recommended:
#Override
public void onBackPressed() {
// make sure you have this outcommented
// super.onBackPressed();
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
To exit from an Android app, just simply use.
in your Main Activity, or you can use Android manifest file to set
android:noHistory="true"
finish your current_activity using method finish() onBack method of your current_activity
and then add below lines in onDestroy of the current_activity for Removing Force close
#Override
public void onDestroy()
{
android.os.Process.killProcess(android.os.Process.myPid());
super.onDestroy();
}
I modified #Vlad_Spays answer so that the back button acts normally unless it's the last item in the stack, then it prompts the user before exiting the app.
#Override
public void onBackPressed(){
if (isTaskRoot()){
if (backButtonCount >= 1){
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}else{
Toast.makeText(this, "Press the back button once again to close the application.", Toast.LENGTH_SHORT).show();
backButtonCount++;
}
}else{
super.onBackPressed();
}
}
you can simply use this
startActivity(new Intent(this, Splash.class));
moveTaskToBack(true);
The startActivity(new Intent(this, Splash.class)); is the first class that will be lauched when the application starts
moveTaskToBack(true); will minimize your application
Add this code in the activity from where you want to exit from the app on pressing back button:
#Override
public void onBackPressed() {
super.onBackPressed();
exitFromApp();
}
private void exitFromApp() {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
}

Android: How to go back previous application on back button click [duplicate]

I want to do something simple on android app.
How is it possible to go back to a previous activity.
What code do I need to go back to previous activity
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: http://developer.android.com/reference/android/content/Intent.html
As mentioned in the comments, if the activity is opened with startActivity() then one can close it with finish().
If you wish to use the Up button you can catch that in onOptionsSelected(MenuItem item) method with checking the item ID against android.R.id.home unlike R.id.home as mentioned in the comments.
Try Activity#finish(). This is more or less what the back button does by default.
Just write on click finish(). It will take you to the previous Activity.
Just this
super.onBackPressed();
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
This will get you to a previous activity keeping its stack and clearing all activities after it from the stack.
For example, if stack was A->B->C->D and you start B with this flag, stack will be A->B
Just call these method to finish current activity or to go back by onBackPressed
finish();
OR
onBackPressed();
Are you wanting to take control of the back button behavior? You can override the back button (to go to a specific activity) via one of two methods.
For Android 1.6 and below:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
// do something on back.
return true;
}
return super.onKeyDown(keyCode, event);
}
Or if you are only supporting Android 2.0 or greater:
#Override
public void onBackPressed() {
// do something on back.
return;
}
For more details: http://android-developers.blogspot.com/2009/12/back-and-other-hard-keys-three-stories.html
Try this is act as you have to press the back button
finish();
super.onBackPressed();
Add this in your onCLick() method, it will go back to your previous activity
finish();
or You can use this. It worked perfectly for me
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if ( id == android.R.id.home ) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
if you want to go to just want to go to previous activity use
finish();
OR
onBackPressed();
if you want to go to second activity or below that use following:
intent = new Intent(MyFourthActivity.this , MySecondActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//Bundle is optional
Bundle bundle = new Bundle();
bundle.putString("MyValue1", val1);
intent.putExtras(bundle);
//end Bundle
startActivity(intent);
If you have setup correctly the AndroidManifest.xml file with activity parent, you can use :
NavUtils.navigateUpFromSameTask(this);
Where this is your child activity.
Got the same problem and
finish(); OR super.onBackPressed();
worked fine for me, both worked same, but no luck with return
You can explicitly call onBackPressed is the easiest way
Refer Go back to previous activity for details
Start the second activity using intent (either use startActivity or startActivityForResult according to your requirements). Now when user press back button, the current activity on top will be closed and the previous will be shown.
Now Lets say you have two activities, one for selecting some settings for the user, like language, country etc, and after selecting it, the user clicks on Next button to go to the login form (for example) . Now if the login is unsuccessful, then the user will be on the login activity, what if login is successful ?
If login is successful, then you have to start another activity. It means a third activity will be started, and still there are two activities running. In this case, it will be good to use startActivityForResult. When login is successful, send OK data back to first activity and close login activity. Now when the data is received, then start the third activity and close the first activity by using finish.
You can try this:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
All new activities/intents by default have back/previous behavior, unless you have coded a finish() on the calling activity.
#Override
public void onBackPressed() {
super.onBackPressed();
}
and if you want on button click go back then simply put
bbsubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
I suggest the NavUtils.navigateUpFromSameTask(), it's easy and very simple, you can learn it from the google developer.Wish I could help you!
#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.
There are few cases to go back to your previous activity:
Case 1: if you want take result back to your previous activity then
ActivityA.java
Intent intent = new Intent(ActivityA.this, FBHelperActivity.class);
startActivityForResult(intent,2);
FBHelperActivity.java
Intent returnIntent = new Intent();
setResult(RESULT_OK, returnIntent);
finish();
Case 2: ActivityA --> FBHelperActivity---->ActivityA
ActivityA.java
Intent intent = new Intent(ActivityA.this, FBHelperActivity.class);
startActivity(intent);
FBHelperActivity.java
after getting of result call finish();
By this way your second activity will finish and because
you did not call finish() in your first activity then
automatic first activity is in back ground, will visible.
Besides all the mentioned answers, their is still an alternative way of doing this, lets say you have two classes , class A and class B.
Class A you have made some activities like checkbox select, printed out some data and intent to class B.
Class B, you would like to pass multiple values to class A and maintain the previous state of class A, you can use, try this alternative method or download source code to demonstrate this
http://whats-online.info/science-and-tutorials/125/Android-maintain-the-previous-state-of-activity-on-intent/
or
http://developer.android.com/reference/android/content/Intent.html
Just try this in,
first activity
Intent mainIntent = new Intent(Activity1.this, Activity2.class);
this.startActivity(mainIntent);
In your second activity
#Override
public void onBackPressed() {
this.finish();
}
First, thing you need to keep in mind that, if you want to go back to a previous activity. Then don't call finish() method when goes to another activity using Intent.
After that you have two way to back from current activity to previous activity:
Simply call:
finish()
OR
super.onBackPressed();
To go back from one activity to another by clicking back button use the code given below use current activity name and then the target activity.
#Override
public void onBackPressed() {
// do something on back.
startActivity(new Intent(secondActivity.this, MainActivity.class));
return;
}

Android - Close all activities (FLAG_ACTIVITY_CLEAR_TOP/clearTaskOnLaunch didn't help)

I have "MainMenuActivity" in my application, from which I want to log out. After pressing the back button, this activity should start "Logout activity", which does some logout stuff and then finishes the application.
Method called onBackPressed() from MainMenuActivity:
public static void logoutAction(final AbstractActivity activity) {
Builder dialog = new AlertDialog.Builder(activity);
dialog.setPositiveButton(R.string.dialog_btn_yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent();
i.setClass(activity, iess.student.login.LogoutActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
activity.startActivity(i);
activity.finish();
}
});
dialog.show();
}
Then, "LogoutActivity" executes AsyncTask, which at the end of its work calls finish() on LogoutActivity.
My problem is, that if other activities were launched before MainMenuActivity, i.e. A -> B -> MainMenuActivity, then after pressing back button Logout activity does its work, finishes, but instead of closing the application, activity B comes to front. I tried to launch MainMenuActivity from activity B with FLAG_ACTIVITY_CLEAR_TOP and then call finish() on B, but in that case A came to front. I also tried to set:
<activity android:name="abc.def.LogoutActivity" android:clearTaskOnLaunch="true"></activity>
But the result was the same as before. Could you please help me what should I do?
OK, so I finally managed it. After creating an activity, I register it in static ArrayList<Activity>. After "LogoutActivity" does its work; it just calls finish() on each Activity registered in ArrayList. It works, but I guess it's not really nice. But I haven't figured out how to do this with FLAG_ACTIVITY_CLEAR_TOP.
As #sandrstar says in the comment:
from API 11 you can use FLAG_ACTIVITY_CLEAR_TASK
It works very well for me, as it removes all Activities, not just the ones on top.

Categories

Resources