Difference between finish () and onBackPressed()

Well as the title indicates, what is the difference between the method finish() and onBackPressed()?

 4
Author: borjis, 2016-10-28

5 answers

finish() destroy an activity and you won't be able to access it until you create it again.

onBackPressed() go back to the previous activity or fragment that you are in the moment, it all depends on how you programmed it.

For example if when changing activity you destroy the previous one with finish(), when doing onBackPressed() it will not find the previous one and you will close the application which can give you the feeling that it is a finish() but it is not, it has only put the app second flat (I think because of this you can have the confusion).

Activity A - > Activity B finish() - > Activity C

In this case if you are in the activity C and you do a onBackPressed() you will return to activity A.

Activity B finish() - > Activity C

In this case if you are in the activity C and do a onBackPressed() leave the app in the background

 9
Author: Fabio Venturi Pastor, 2017-03-07 18:48:59

Finish ()

Is a function to end the activity, taking it out of the activity stack.

Navigation between activities naturally

A->B->C pressing back C->B->A

If finish() is used in some activity

A->B(finish)->C press back C->A

A case study would be a splashcreen, which when it finishes loading will move to another activity, but removing it from the stack, so if the user performs the back action, it will exit the app.

SplasCreenActivity.java

startActivity(new Intent(this,MainActivity.class));
finish();

OnBackPressed ()

Is to detect the go back event, when the user performs the go back action, using the physical, virtual, or UpNavButton

@Override
public void onBackPressed() {
...
}

The uses can be varied, prevent the exit of the app while there is some task in operation, compute the double press to exit the app...

 3
Author: Webserveis, 2016-10-28 11:57:47

The back button defaults to finish() but if you want to overwrite this method, add code before it goes back and finishes a Activity you must create the onBackPressed() method.

There is also the way to identify when the back button is pressed

@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
    if ((keyCode == KeyEvent.KEYCODE_BACK))
    {
        //codigo adicional
        finish();
    }
    return super.onKeyDown(keyCode, event);
}

But the right thing would be :

@Override
public void onBackPressed() {
        super.onBackPressed();
        //codigo adicional
        this.finish();
}

Edition

When writing the method onBackPressed() the user should know why he writes the method, if he wants to return to the Activity previous without not making any changes does not make sense. However, I will give an example. If we want to modify the rollback event and warn the user "you are sure to exit" it is indicated about writing this method and tell the method to return to the previous Activity or to the one that the user wants.

I quote @FabioVenturiPastor

For example if you close the previous activity with finish () when you do onBackPressed () you will not find the you will close the application which can give you the feeling that it is a finish() but it is not, it has only put the app in the background (I think that for this you can have the confusion).

As explained above, if the user over writes the method and does not make any kind of additional code and also does not specify that activity should return it makes no sense at all.

 2
Author: sioesi, 2016-10-28 14:40:07

Finish ()

Finish() : when this method is called the Activity is closed and destroyed. this method can be called where necessary, for example activated when interacting by some element in the UI or when performing some action in our application.

myButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //llama finish() para cerrar Activity.
                finish();

            }
        });

OnBackPressed ()

OnBackPressed(): when you implement this method unlike finish () is called exclusively when you click to the "back" button and you don't need to call finish() explicitly inside it, this if you call super.onBackPressed() since internally it calls finish() .

@Override
public void onBackPressed() {
        //Si llamas super.onBackPressed(), esto internamente ejecuta finish().
        super.onBackPressed();            
}

If you don't call super.onBackPressed() and want to finish the Activity, you would have to call finish():

@Override
public void onBackPressed() {

     finish();            

}

Something important is that both methods being in an Activity and having a back stack void can close the application this If onbackpressed () calls finish ().

As a summary, finish () finishes the activity and destroys it, while onbackpressed () can detect when we activate the "back" button, detects the "back" event and internally executes finish().

 1
Author: Jorgesys, 2016-10-29 14:33:48

The finish () method will terminate the activity and the onbackpressed() method will be executed when the user presses the virtual backspace key. To supplement and since there is not much information about these methods for fragments that is what I work with. If we want to end the activity in a fragment it will be:"it is in a fragment"

@Override
public void onClick(View v){
   getActivity.finish()
}

If you are working with fragments and you want an alert to appear when you press the back button to say whether or not you want to exit the application, the code you must do in the main activity where all the call of fragments began. "it is in the main_activity":

@Override
public void onBackPressed() {
    AlertDialog.Builder mensaje=new AlertDialog.Builder(this);
    mensaje.setTitle("¿Desea Salir de la Aplicacion?");
    mensaje.setCancelable(false);
    mensaje.setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            finish();
        }
    });
    mensaje.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
        }
    });
    mensaje.show();
}
 1
Author: Jose A. Huanca Ancajima, 2018-01-17 08:23:30