Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 640
Mark Avatar asked Jul 05 '12 15:07

Mark


People also ask

Is onCreate only called once?

OnCreate is only called once.

When onCreate function is called in Android?

We do not call the onCreate() method ; it is called automatically when you start an Activity from intent.

What is the name of the method which is use to get intent data in onCreate ()?

There is no difficulty using intents to start NextActivity from within MainActivity if the getIntent() method is called inside the onCreate() block of NextActivity : public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.

Why is onCreate called twice?

onCreate will get called when your activity has been destroyed and recreated, which happens any time the device is rotated, the keyboard is opened, or you switch apps and the system decides it's time to reclaim some memory and kill off your app.


1 Answers

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().

like image 135
David Wasser Avatar answered Nov 03 '22 02:11

David Wasser