Not to destroy current activity on back button is pressed - android

I have two activities, A and B. I have a button in A,when pressed starts a new intent to B.
However whenever I press the back button while in B, than click the button again is restarts Activity.I do not want to do that,I want it to resume Activity B.
Actually I am doing some networking in Activity B and I want to save unless the user wants to refresh.
How can I do it? Thanks in advance

Use
#Override
public void onBackPressed(){
moveTaskToBack(true);
}
Hope, It must help you

You need to Overrider the
onBackPressed
method and start there the activity like this:
#Override
public void onBackPressed() {
Intent intent = new Intent(this, activityA.class);
startActivityForResult(intent, PICK_CONTACT_REQ);
}

This sounds like you need to rethink your architecture. You say:
Actually I am doing some networking in Activity B and I want to save
unless the user wants to refresh.
If this is the case, you probably don't want to do your networking in ActivityB. Maybe you should start a Service from ActivityB to do the networking. The service and the activity can communicate with each other so that the activity can keep the user up-to-date about the state of the networking. If the user presses BACK in ActivityB, it can finish (as usual) and return to ActivityA. In this case, the Service is still managing the networking. When the user again starts ActivityB (from ActivityA), the new instance of ActivityB can communicate with the service to see if there is any networking going on, and if so it can get the current status of that networking or start it or stop it or whatever.

I guess I'm too late but I had a similar problem.
I had two activities A,B and a next button in A.
Whenever I tried to do: A->press next button ->B->press back button->A->press next button->B, B screen got destroyed when I pressed the back button. So when I came back to B for the second time it was a newly created B (all the information I had put in was gone).
So it was like A->B->A->new B when I just wanted to go back to the original B! :(
So what I did was, in activity B, I overrode the onBackPressed() function so it doesn't destroy the activity. I also set the flag so that if there is a A activity already running, it would just pull it up to the front instead of creating a new A activity.
#Override
public void onBackPressed() {
Intent intent = new Intent(getApplicationContext(), ActivityA.class);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
}
Then, for the onclicklistener function for the next button in activity A, I set the flags similarly.
public void onClickNextbutton(View v){
Intent intent = new Intent(getApplicationContext(), ActivityB.class);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
}

Related

How does one navigate back more than one screen?

I've been trying the new Navigation component and so far so good. However, I've hit a wall when it comes to the following. My question is best described with an example, so let me give one.
I think it's a very common scenario that apps have a login screen and then they forward the user to a home screen, or dashboard, or something similar. Let's stick to the naming - LoginScreen and HomeScreen.
Say the app is very simple. It starts at the LoginScreen and as soon as the user logs in, they're forwarded to the HoneScreen. Pretty simple app, but serves the example.
Now, if the user hits back, how do we exit the app? So far it always takes me to the LoginScreen.
Further evolving on this example. Imagine there's a welcome screen before the login screen where the user can decide to login or register. How would one deal with navigating back in this case too?
Essentially, I'm asking if there's a built in functionality in the navigation component that let's you go back more than one screen and if not, is there a way to achieve this? Thank you very much.
#Fred
To achieve this you can finish each activity after having started the other one. For example the WelcomeScreen has called LoginScreen you can directly finish it and when LoginScreen calls HomeScreen finish LoginScreen so when the user will navigate back from HomeScreen all activities will be closed.
Or, from the present activity you can call System.exit(0) to exit the application. This serves when you have many activities but if you have one there will be no difference with finish()
Another scenario is as you described in comments:
Consider you have following activities: ActivityA, ActivityB and ActivityC and you want to come back to ActivityA from ActivityC without passing by ActivityB. If you ActivityA has been previously opened you can bring it back to front, depending on when you want this to be done. With our sample we consider when the activity finishes:
#Override
protected void onDestroy() {
super.onDestroy();
//this will bring the ActivityA on the front
Intent intent=new Intent(this,ActivityA.class);
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
}
Or you may have a different scenario where the LoginActivity is started only if the is not already connected otherwise you do directly to HomeScreen. In this case, I create a Singleton that will help me register the current calling activity so that I can know which activity will be directly started after successful login.
For example:
if(sharedPreferences!=null) {
if (sharedPreferences.getBoolean("user_connected",false)){
startActivity(new Intent(this, HomeScreen.class));}
else
{
MySingleton.getInstance().setCurrentCallingActivity("HomeScreen");
startActivity(new Intent(this, LoginActivity.class));
}
}
And once in LoginActivity, after a successful login, I do the following:
try
{
startActivity(new Intent(this,
getClassLoader().loadClass(MySingleton.getInstance().getCurrentCallingActivity())));
finish();
}catch (ClassNotFoundException e)
{
//your code
finish();
}
That's how I handle that and it works. Up to you to see a corresponding scenario and try if it can work. Different approches may coexist and this far from being performant.
You could try this:
Intent myIntent = new Intent(LoginScreen.this, HomeScreen.class);
startActivity(myIntent);
finish(); //finish LoginScreen, then when press back in HomeScreen, it will exit instead return LoginScreen
First of all you need to see if u prefer to use Activity or Fragments.
if you want to remove all Fragments in the stack then you need to use
FragmentManager fms = getSupportFragmentManager();
for (int i = 0; i < fms.getBackStackEntryCount(); ++i) {
fms.popBackStack(); }
If you want to remove specifc Fragment than you will have to use tags.
Fragment fragment = getSupportFragmentManager().findFragmentByTag(TAG_FRAGMENT);
if(fragment != null)
getSupportFragmentManager().beginTransaction().remove(fragment).commit();
Now about Activity you need to consider a few options
Activity A is your Login.
Activity B is your Register page.
Activity C is your Homepage.
if you want to move from A to C after Successful login than use
Intent intent = new Intent(Login.this, MainActivity.class);
startActivity(intent);
finish();
if you want to move from A to B
Intent intent = new Intent(Login.this, Register.class);
startActivity(intent);
if you want to move from A to B and after Register success move to C than use :
Intent intent = new Intent(LoginSM.this, MainActivitySM.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();

Back button from activity 2 closes down the app instead of going to activity 1 in Android 7

Pressing back button from the second activity returned to the first activity before without problems. I then updated to Android 7.
Then the whole app closed when pressing back button from the second activity.
I know that there are threads about this here and I have checked them all. Basically, they say that finish() should be avoided from the first activity.
I don't call finish(), so that is the problem here. It is difficult to solve, because it works like it should when I launch the app from Android studio.
It returns to the first activity from second. The problem occurs when the app is started by pressing its icon (not from Android studio).
Pressing back from the second activity closes down the whole app. How can I solve this? Here is some of my code:
Activity 1:
Intent glIntent = new Intent("astral.worldstriall.GLActivity");
glIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
The below code should be used in 2nd activity so that when u press back button it terminates the current activity(2nd activity) and goes back to previous activity
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
I think you just misused the Intent constructor. According to the documentation, you used this constructor Intent(String action). The one that you atually want should be this one Intent(Context packageContext, Class<?> cls).
In the first activity (therefore this being the instance of your first activity), you should write:
Intent glIntent = new Intent(this, astral.worldstriall.GLActivity.class);
glIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(glIntent);
For going first to second activity...
Intent i=new Intent(FirstActivity.this,SecondActivity.class);
startActivity(i);
Use below code for going in previous activity...
#Override
public void onBackPressed() {
super.onBackPressed();
Intent i=new Intent(SecondActivity.this, FirstActivity.class);
startActivity(i);
}

Exclude Activity from recents and history

Actually I have a direct issue with android custom tabs.
But nevertheless I will generalize my question. Let's assume that I have ActivityA and ActivityB. ActivityA - is an external one, so that we launch it from an Intent :
Intent intent = customTabsIntent.intent;
intent.setData(requestUri);
intent.putExtra(CustomTabsIntent.EXTRA_TITLE_VISIBILITY_STATE, CustomTabsIntent.NO_TITLE);
mContext.startActivity(intent);
From here we see that ActivityA - is actually a custom tab activity. When things get done I launch ActivityB. I want ActivityA dissaper from task history, I can achieve this by aplying flag Intent.FLAG_ACTIVITY_NO_HISTORY to my intent. But this approach is causing problems, because when user switches to recents,or goes to other app - ActivityA disappears forever. Of course - that's how flag no history works. But I want a different flow, I want ActivityA disappear only when ActivityB was launched. Any ideas how to achieve this?
P.S. I need to finish ActivityA, which gets launched via intent, I don't have access to its code and I don't have the ability to call finish().
I don't think you can do this by using the NO_HISTORY flag since ActivityA is doing the launching and you have no control over it.
However, you should be able to achieve your goal (not being able to go from ActivityB back to ActivityA by overriding the BACK button in ActivityB and having it go back to whatever is underneath ActivityA in the task stack.
Assuming that ActivityC is the one that starts ActivityA, you could do something like this in ActivityB:
#Override
public void onBackPressed() {
// Direct user back to ActivityC
Intent intent = new Intent(this, ActivityC.class);
// Add flags to ensure that we reuse the existing instance of
// ActivityC and that we clear any other activities above ActivityC
// from the stack.
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
}
You can use finish() method to clear any activity. so before starting another activity finish that.
Intent intent = customTabsIntent.intent;
intent.setData(requestUri);
intent.putExtra(CustomTabsIntent.EXTRA_TITLE_VISIBILITY_STATE, CustomTabsIntent.NO_TITLE);
mContext.startActivity(intent);
finish(); //add this to clear that activity

Android - Activity Hierarchy (back button)

I have the following model:
MainActivity navigates (through a button) to ActivityA.
ActivityA displays list of records as a ListView (from SQLite database).
If I click on any record, an intent will start ActivityB which displays the data of the selected record to be edited.
If I press on the device back button it will take me back to ActivityA.
ActivityB has a 'save' button, which if clicked will open new intent of ActivityA with the updated records (after edit), also, this button will finish() ActivityB.
Here if I press the device back button (after saving ActivityB and opening ActivityA), it will take me to the old ActivityA with the data before update (the older version of ActivityA), then on the second click on device back button, it will go back to MainActivity.
The question is: How can I let the device back button always go back to the hierarchical parent, instead of going to previous open activities?
OR
How can I kill the old instance of ActivityA if the user clicks on the save button in ActivityB?
Your help is appreciated.
In ActivityB, after the save, you should call finish() instead of opening a new instance of ActivityA. You should have ActivityA re-query and update the ListView.
You can specify FLAG_ACTIVITY_CLEAR_TOP flag in the Intent used to launch ActivityA.
Intent intent = new Intent(this, ActivityA.class);
intent.setFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP );
startActivity(intent);
If ActivityA being launched is already running in the current task, then all of the other activities on top of it will be closed including ActivityA and ActivityA is restarted with the new Intent. There will be no need to call finish() on ActivityB explicitly.
Just add finish() in OnPause() of ActivityA and
add this method to ActivityB.
#Overrride
public void onBackPressed(View v) {
Intent MainActivityIntent = new Intent(ActivityB.this, ActivityA.Class);
startActivity(MainActivityIntent);
super.onBackPressed();
}
just try this, it really works...

How to remove all activity in Stack when press back button

I have a list of activities A - B -C -D - E and more, for example final activity is K. I want clear all these activities in stack when i press BACK button. How can i do ? In fact, i over ride
onBackPress(){
moveTaskToBack(true);
finish();
}
but only current activity is deleted and application exit. Then, i come back application, it resume activity before K. I want it start from begining when i re-open app. I think the reason here is because the list of activities in stack still are stored, so i want to clear all stack when clicking BACK button. Any suggestions ? thank you very much !
There is method called finishAffinity() for finishing all activity.
public void onBackPressed(){
super.onBackPressed();
this.finishAffinity();}
You need to call your activity with the FLAG_ACTIVITY_CLEAR_TOP inside your onBackPressed
#Override
public void onBackPressed()
{
Intent it = new Intent(YouCurrentActivity.this, YourFinalActivity.class);
it.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(it);
finish();
}
Hope it Helps!
Either use the noHistory flag in the manifest or finish each activity yourself when the user navigates away.
startActivity(myIntent);
finish();
Another solution, maybe the best, if you have so many overlaying Activities: use only one Activity and handle the content in Fragments. This way you are in control what exactly you want to show when the user hits the back button.
In API level 11 or greater, use FLAG_ACTIVITY_CLEAR_TASK and FLAG_ACTIVITY_NEW_TASK flag on Intent to clear all the activity stack.
Add this code on your onBackPressed() method,
> This launch mode can also be used to
good effect in conjunction with
FLAG_ACTIVITY_NEW_TASK: if used to
start the root activity of a task, it
will bring any currently running
instance of that task to the
foreground, and then clear it to its
root state. This is especially useful,
for example, when launching an
activity from the notification
manager.
So your code to launch B would be:
Intent intent = new Intent(A.this, B.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish(); // call this to finish the current activity

Categories

Resources