Detect onBackPressed () from the main activity

1

I have an application with a button that takes us from Activity A (Main) to Activity B, I would like that when I close activity B with an onBackPressed () the application A (Main) will detect that it is the activity again active and act by making a method, is that possible?

Thanks in advance,

Edit1:

Code in MainActivity ()

        botonActividadB.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent a = new Intent(MainActivity.this, ActividadB.class);
            MainActivity.this.startActivity(a);
        }
    });

Code in ActivityB

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

My intention is for onBackPressed to have MainActivity execute a method, without the need to pass parameters between MainActivity and ActivityB, so how do I get MainActivity to detect which ActivityB has finished?

    
asked by Macia Estela 13.06.2018 в 23:22
source

1 answer

0

You can do it using startActivityForResult() , in your MainActivity define a variable with a value that you determine returns from Activity B:

  private static final int VALOR = 12;

Add the onActivityResult() method, which will be the one that will receive the information.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    Log.i("MainActivity", "onActivityResult() requestCode : " +requestCode);
    if (requestCode == VALOR){

        switch (resultCode) {
            case RESULT_OK:
                Log.i("MainActivity", "onActivityResult() RESULT_OK");
                break;

            case RESULT_CANCELED:
                Log.i("MainActivity", "onActivityResult() RESULT_CANCELED");
                break;
        }
    }
}

and perform the Intent in this way:

Intent intent = new Intent(this, MainActivity3.class);
startActivityForResult(intent, CHILD_REQUEST);
setResult(RESULT_OK, intent);

in this way when you finish Activity B using the method

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

You will get the result in MainActivity within the onActivityResult() method, check out this excellent tutorial in Spanish:

link

    
answered by 14.06.2018 / 01:41
source