Home » Android » Detect that an activity has closed in Android

Detect that an activity has closed in Android

Posted by: admin June 15, 2020 Leave a comment

Questions:

In my application I need to launch a SelectionActivity to select one of the options. Once the option has been selected I need to refresh another list on the MainActivity.

This is the code that I use to launch the SelectionActivity:

Intent intent = new Intent(MainActivity.this, SelectionActivity.class);
startActivity(intent);

In SelectionActivity this is the code that receives the selected option an closes the activity:

selectedValue = adapter.getItem(position);
finish();

Now the application comes back to MainActivity but I don’t know how to receive an event that the SelectionActivity has closed.

Thanks

How to&Answers:

Look into startActivityForResult()

Answer:

Quick snippet showing use of startActivityForResult:

private static final int MY_REQUEST_CODE = 0xe110; // Or whatever number you want
// ensure it's unique compared to other activity request codes you use

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

    if (requestCode == MY_REQUEST_CODE)
        ActiviyFinishedNowDoSomethingAmazing();
}

public void onClickStartMyActivity(View view)
{
    startActivityForResult(new Intent(this, GameActivity.class), MY_REQUEST_CODE);
}

More reading on getting a result from an activity.

Answer:

Depending on your application’s design you can refresh the list each time the Main activity is returned to by watching the onResume() or onRestart() events. In addition there is startActivityForResult(). All of these methods are in Activity.

Answer:

Solution 1 :

  1. Make selectedValue a static public variable.
  2. In your MainActivity :

    void onResume() {
            result = SelectionActivity.selectedValue;
    }
    

Solution 2 :

If the SelectionActivity‘s job is simply a selection from multiple options, Consider using Dialogs

Answer:

startActivityForResult(), then override the onActivityResult() method. There are a lot of examples one can google for just using the key word startactivityforresult.

Answer:

Use onActivityResult() or make selectedValue static. In MainActivity use the onResume method:

protected void onResume() {
    if(SelectionActivity.selectedValue != 0)
          newValue = SelectionActivity.selectedValue;
}

Answer:

Use onDestroy:

public void onDestroy() {
    super.onDestroy();

    Log.w("test", "active");
}