Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if Activity came to front due to back navigation

I'd like to know if my Activity was displayed because the user pressed back on some other Activity. In the Lifecycle I couldn't identify any Callbacks that are robustly giving me that info.

onRestart() is not working. It will also fire if the Apps Task was brought to front. onResume() will not work for the same reason.

I suppose there is a simple solution for that, but in Android supposedly simple things can be pretty nasty.

like image 238
Jakob Avatar asked Aug 28 '12 12:08

Jakob


People also ask

How do I check foreground activity?

In your finish() method, you want to use isActivityVisible() to check if the activity is visible or not. There you can also check if the user has selected an option or not.

How can I get back the result from one activity to main activity or other activity?

Put the data that you want to send back to the previous activity into an Intent . The data is stored in the Intent using a key-value pair. Set the result to RESULT_OK and add the intent holding your data. Call finish() to close the Second Activity.

Which method is used to call another activity when we expect to get something back from the called activity?

By the help of android startActivityForResult() method, we can get result from another activity.

Which life cycle method is called when activity is sent to the background?

The onPause() and onResume() methods are called when the application is brought to the background and into the foreground again.


1 Answers

Call your 2nd activity with startActivityForResult(Intent, int), then override the onBackPressed() in the 2nd activity and have it setResult() to RESULT_CANCELED. Lastly, have the 1st activity catch that in onActivityResult().

Code example:

Activity 1:

Intent i = new Intent(Activity1.this, Activity2.class);
startActivityForResult(i, 0);

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

    if (requestCode == 0) {
        if (resultCode == RESULT_CANCELED) {
                // user pressed back from 2nd activity to go to 1st activity. code here
        }
    }
}

Activity 2:

@Override
public void onBackPressed() {
    setResult(RESULT_CANCELED);
    finish();
}
like image 194
Mxyk Avatar answered Oct 10 '22 19:10

Mxyk