Home > Net >  Why do codes work in the onCreate() instead of onResume()
Why do codes work in the onCreate() instead of onResume()

Time:06-14

I'm like an intermediate in android programming. I decided to take a deep dive into the Activity lifecycle methods and I realised something, like why do methods Toasts.show() and many other methods get called again when the activity is resumed. If the methods are in the onCreate so why then if you like go to another activity and return it will still give you a Toast message. Let me give an example.

public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

{Your Initialization go here }


 //Toas message 
 Toast.makeText(code).show();
 }
 }

So imagine you leaving this activity for another one and then coming back... why does it still show the Toast message. Because since the lifecycle is OnCreate onResume onStart onPause onstop onDestroy

And when you come back to your MainActivity it calls the onResume onStart. So if onCreate is not called...So how does the Toast message show. Please someone should help me answer this I've searched all day but couldn't find answers.

CodePudding user response:

accoording to lifecycle of activity enter image description here

CodePudding user response:

When your activity goes in the background, and memory is required for other apps. It is possible that the system frees up space even though your activity is in the background with ONPAUSED state. and now if you navigate to your activity, since the saved instance is removed due to memory requirements. instead of ONRESUME, ONSTART is called. you can read more about it here: https://developer.android.com/guide/components/activities/activity-lifecycle and see this image for better understanding: https://developer.android.com/guide/components/images/activity_lifecycle.png

This uncertainty is one of the reasons why we now mostly use view models for a sizeable app.

  • Related