I am trying to understand what happens under the hood when the user presses on back and I did not overwrite onOptionsItemSelected
.
I have the following scenario:
intent.putExtra("abc", "abc");
getIntent()
in onCreate()
What exactly happens when the user clicks back in activity C?
If I don't overwrite the back button, pressing back will produce a nullException on the getIntent line. Why? It's in onCreate()
not in onStart()
.
If I use onSaveInstanceState
the bundle is always empty. This leads me to assume that back is creating a new instance of the Activity. Why? It should just finish itself.
If I overwrite the back button with finish()
it no longer crashes but I thought the default behavior of back is to run finish()
.
EDIT with more details:
I put a toast in each of the lifecycle methods and I found out that Activity B calls on destroy after I press back on Activity C. This makes no sense to me!
Manifest:
Activity A
<activity
android:name=".activities.MainActivity"
android:configChanges="orientation"
android:screenOrientation="portrait"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Activity B
<activity
android:name=".activities.MenuActivity"
android:configChanges="orientation"
android:screenOrientation="portrait"
android:label="@string/menu_title"
android:parentActivityName=".activities.MainActivity">
</activity>
Activity C
<activity
android:name=".activities.OptionActivity"
android:configChanges="orientation"
android:screenOrientation="portrait"
android:label="@string/option_title"
android:parentActivityName=".activities.MenuActivity">
</activity>
Why does Activity B get destroyed when I click back on Activity C ?
Are you using intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
for intent before starting your activity. It will clear the backstack
and when you press back, the activity will be recreated.
UPDATE:
Don't rely on the call for onDestroy()
as it may or may not be called on back button press.
However it is guaranteed to be called on a call to finish()
but is not surely gets called on a back button press.
Activity OnDestroy never called?
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