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.
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.
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.
By the help of android startActivityForResult() method, we can get result from another activity.
The onPause() and onResume() methods are called when the application is brought to the background and into the foreground again.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With