Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OnCreate runs after back button is pressed

Tags:

android

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:

  1. Activity A with intent.putExtra("abc", "abc");
  2. Activity B with getIntent() in onCreate()
  3. Activity C

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>
like image 648
Mika Avatar asked Jul 03 '14 10:07

Mika


1 Answers

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?

like image 65
My God Avatar answered Oct 10 '22 23:10

My God