ChatGPT解决这个技术问题 Extra ChatGPT

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.

You do not even need a back button, just let the user used the phone back key and you do not have to do anything.
Phones back button closes entry application, not just my secondary activity. I don't want to close the main activity.
The 'back' button should not do that -- can you show more of your code?
Responding to your edit, the secondary activity looks good from what you've posted. I think TGMCians probably has the right answer and you investigate your manifest.
see this answer i think this will help you

M
MSS

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.


That would explain why the phone's 'back' button also dismisses the main activity.
When debugging, I noticed execution continues after finish(), so it's advisable to put a return in addition.
Isn't the third reason in this answer just a repeat of the first?
j
jjNford

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.


"Note any code after the finish() call will be run - you can just do a return after calling finish() to fix this" I think 'fix' is a bad choice of words here. It's more like you're avoiding execution of the following lines (not fixing).
O
Osama Ibrahim

if you use fragment u should use

getActivity().onBackPressed();

if you use single activity u can use

finish();

Z
Zabador

When you click your button you can have it call:

super.onBackPressed();

T
Trevor

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>
...

N
Nirav Gadhiya

try this code instead of finish:

onBackPressed();


Works fine for going back from ActivityB to ActivityA. For fragments and single activities could use @Osama Ibrahim's answer.
J
JJD
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();
    }
});

E
Eric Leschinski

This closes the entire application:

this.finish();

This closes the entire application as stated int he question, not just the current activity, As does the phones back button ?
How do I got to previous activity from Camera activity.
No, it doesn't. It only closes current activity. See: developer.android.com/reference/android/app/…
p
peejaybee

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


u
user2742861

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.


P
Puni
 @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.


This one worked for me. I also had a MainActivity and a SettingsActivity with android:parentActivityName=".MainActivity" for the second one. This code handles that Home/Back button in the toolbat and just finishes the current activity returning to the previous one in the stack. Thanks.
K
Kent Hansen

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) ?


Does this answer the question ? Or is this only a suggestion to be tried ? In both cases, the rant is unnecessary and likely not welcome on SO
R
Raven

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.


H
Hagos Alema

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.


c
codeMagic

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


I tried this route, but I have about 10 screens in sequence that use high resolution PNGs. The problem is, by about screen 7, the device out of memories due to all the activities in the back-stack. I decided to call finish on each activity, and this fixed the issue by allowing garbage collection, but now the back behavior needs coded manually because the back-stack is now empty. Have you run into this problem or know of any mechanisms in Android to address this?
What do you want the back button to do? Go back to whatever the previous Activity was or always go back to the MainActivity? Also, if you are running out of memory with Bitmaps then you should read This part of Docs. It helped me
@Lo-Tan if you are wanting to go back to the previous activity then I think you need to figure out memory management for your images and not finish the activities (maybe with the link I provided). Otherwise, you will have to recreate a new instance of the activity and try to figure out which one to go back to
I would like the back button to just go to the previous screen. This is a series of tutorial screens, basically, and the user can go forward/back. Each screen is designed and uses lots of pngs - sometimes pngs that take up most of the screen (not just little thumbnails) so it's sucking up a lot of memory for each screen.
@Lo-Tan I think you want to override the onBackPressed() method and then just manually create the activity to which you want to go to. You can then end the one you are on and startup the previous one.
r
raman rayat

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.


R
Rafat

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


M
Machavity
{ getApplicationContext.finish();   }

Try this method..


While this code block may answer the question, it would be best if you could provide a little explanation for why it does so.
A
Ali Zahid

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!