How can I detect if an activity came to focus after pressing the back button from a child activity, and how can I execute some code at that time?
The method you're looking for may be the onResume method you can implements in your mother class ;). You must know that the onResume is also called the first time you launch any activity. Look at the lifecycle of an activity : http://developer.android.com/images/activity_lifecycle.png
Regards,
js's answer is right, but here is some debugged code.
Declare the request code as a constant at the top of your activity:
public static final int OPEN_NEW_ACTIVITY = 12345;
Put this where you start the new activity:
Intent intent = new Intent(this, NewActivity.class);
startActivityForResult(intent, OPEN_NEW_ACTIVITY);
Do something when the activity is finished. Documentation suggests that you use resultCode
, but depending on the situation, your result can either be RESULT_OK
or RESULT_CANCELED
when the button is pressed. So I would leave it out.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == OPEN_NEW_ACTIVITY) {
// Execute your code on back here
// ....
}
}
For some reason, I had trouble when putting this in a Fragment. So you will have to put it in the Activity.
One possibility would be to start your child activity with startActivityForResult() and implement onActivityResult() which will be called when you return from the child activity.
You can also override both the onBackPressed() method and the onOptionsItemSelected() method and put some logic there. For example I put this into my BaseActivity which all the other Activities extends from:
@Override
public void onBackPressed() {
// your logic
super.onBackPressed();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
// your logic
}
return super.onOptionsItemSelected(item);
}