Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

android - onCreate always called if navigating back with intent

I have an activity called HomeActivity that has a SurfaceView and shows a camera preview picture. This activity is quiet heavy and feels slow if you are starting/restarting it.

So I made some investigations and found out, that somehow always the onCreate method is being called. In my opinion this should not happen if the Activity has already been started?

The documentation says : Called when the activity is first created. This is where you should do all of your normal static set up: create views, bind data to lists, etc. This method also provides you with a Bundle containing the activity's previously frozen state, if there was one. Always followed by onStart().

Here is the method, that handles going back:

protected void gotoHome() {
    final Intent intent = new Intent(SomeOtherActivity.this, HomeActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(intent);
}

Edit:

Here is how I am leaving HomeActivity ... nothing special:

final Intent i = new Intent(HomeActivity.this, SomeOtherActivity.class);
startActivity(i);
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Yes, when you want to return to the HomeActivity, you need to use these flags:

intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);

Here's the relevant section from the documentation on Intent.FLAG_ACTIVITY_CLEAR_TOP:

The currently running instance of activity B in the above example will either receive the new intent you are starting here in its onNewIntent() method, or be itself finished and restarted with the new intent. If it has declared its launch mode to be "multiple" (the default) and you have not set FLAG_ACTIVITY_SINGLE_TOP in the same intent, then it will be finished and re-created; for all other launch modes or if FLAG_ACTIVITY_SINGLE_TOP is set then this Intent will be delivered to the current instance's onNewIntent().


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...