Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
747 views
in Technique[技术] by (71.8m points)

android - Why is onDestroy always called when returning to parent activity?

I have a very simple app based on the Building Your First App tutorial. There are two activities: MainActivity invokes DisplayMessageActivity through startActivity().

When entering DisplayMessageActivity, I see:

MainActivity.onStop()

as expected, but when I press the back button to return to the parent MainActivity, I get:

MainActivity.onDestroy()
MainActivity.onCreate(null)
MainActivity.onStart()

The activity always gets destroyed for this very simple application. But according to the documentation (second bullet point), the typical behavior is for the activity to be stopped and restarted in such cases.

Also, onDestroy() does not happen when first starting the child activity, but only once back button is clicked.

Two questions:

  1. Is there a way to prevent parent from being destroyed in the common case?
  2. Why is null being passed to onCreate() here? This prevents me from preserving state through onSaveInstanceState().

Note that I've verified that Settings -> Developer Options -> Apps -> Don't keep activities is unchecked.

Edit:

Here is how the child activity is linked to parent:

    <activity
        android:name="com.example.helloworld.DisplayMessageActivity"
        android:label="@string/title_activity_display_message"
        android:parentActivityName="com.example.helloworld.MainActivity" >
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.example.helloworld.MainActivity" />
    </activity>

Tracing through DisplayMessageActivity.onOptionsItemSelected(), I can see that it's calling Activity.onNavigateUp().

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Thanks to Greg Giacovelli's comments, I found the answer here. The solution was to set android:launchMode="singleTop" to the parent activity.

I still can't understand why such basic information is so unknown and hard to find!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...