Difference between finish () and onBackPressed ()

4

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

    
asked by borjis 28.10.2016 в 13:22
source

5 answers

6

finish() destroys an activity and you will not be able to access it until you recreate it.

onBackPressed() returns to the Activity or Fragment previous to the one you are in at the moment, everything depends on how you have programmed it.

For example, if you change the activity you destroy the previous one with finish() , when doing onBackPressed() you will not find the previous one and the application will close you, which can give you the feeling that it is a finish() but it's not, you just put the app in the background (I think that's why you can have confusion).

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

In this case, if you are in the Activity C and you make a onBackPressed() you will return to Activity A.

Activity B finish() - > Activity C

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

    
answered by 28.10.2016 / 13:33
source
3

finish ()

It is a function to end the activity, taking it out of the stack of activities.

Navigation between activities naturally

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

If finish() is used in some activity

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

A practical case would be a splashcreen, that when it finishes loading, go to another activity, but removing it from the stack, so if the user performs the action go back, it will leave the app.

SplasCreenActivity.java

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

OnBackPressed ()

It is to detect the event back, when the user performs the action of going back, using the physical button, the virtual button or the UpNavButton

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

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

    
answered by 28.10.2016 в 13:49
2

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

There is also a way to identify when the backspace 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 correct thing would be:

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

EDITING

When writing the onBackPressed() method, the user should know why he overwrites it, if he wants to return to the previous Activity without making any change it does not make sense. However, I will give an example. If we want to modify the backward event and warn the user "You are sure to leave" it is indicated on writing this method AND tell the method that you have to return to the previous% Activity or to the user wants .

I quote @FabioVenturiPastor

  

For example, if you change the previous activity with finish (), doing onBackPressed () will not find the previous one and will close the application, which may give you the feeling that it is a finish () but it's not, you just put the app in the background (I think that's why you can have confusion).

As explained above, if the user overwrites the method and does not make any additional code and does not specify which activity should return it does not make any sense.

    
answered by 28.10.2016 в 13:29
1

finish ()

finish () : when it's called this method the Activity is closed and destroyed. This method can be called where it is 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 the "back" button and do not need to call < a href="https://developer.android.com/reference/android/app/Activity.html"> finish () explicitly within it, this if you call super.onBackPressed() since it internally calls finish() .

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

If you do not call super.onBackPressed() and you want to finish the Activity, you should call finish() :

@Override
public void onBackPressed() {

     finish();            

}

Something important is that both methods being in an Activity and having a back stack empty can close the application if onBackPressed () call finish ().

As a summary, finish () ends the Activity and destroys it, while that onBackPressed () can detect when we activate the "back" button, detects the "back" event and internally executes finish() .

    
answered by 28.10.2016 в 13:49
0

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

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

If you work with fragments and want to press the back button to appear an alert that says whether or not you want to exit the application, you must do the code in the main activity where the entire fragment call 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();
}
    
answered by 17.01.2018 в 08:46