问题
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);
回答1:
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().
来源:https://stackoverflow.com/questions/11347161/oncreate-always-called-if-navigating-back-with-intent