Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onCreate vs. onResume/onRestart bevhaviour regarding member variables

When I open an activity I know that I can initialize stuff in the onCreate function.

But what is the behaviour on the OnResume and onRestart function? When are these functions called?

Specifically: I initialize a local member variable in the onCreate function auiqring a reference to a global object. Now, when the user is interrupted, for example, by a call, the activity can be closed. Later, when the user comes back to my view, what is the status of the already initiliazed variable? Do I have to reinitialize everything in the onResume/onRestart functions? So what would be the functional difference opposed to onCreate?

like image 565
Devolus Avatar asked Apr 17 '13 11:04

Devolus


People also ask

What is difference between onStart and onResume?

onStart() -> called when the activity becomes visible, but might not be in the foreground (e.g. an AlertFragment is on top or any other possible use case). onResume() -> called when the activity is in the foreground, or the user can interact with the Activity. Save this answer.

What is the difference between onPause and onResume?

The onResume() method runs after the onStart() method. It gets called when the activity is about to move into the foreground. After the onResume() method has run, the activity has the focus and the user can interact with it. The onPause() method runs when the activity stops being in the foreground.

What is the difference between onCreate () and onStart ()?

onCreate() is called when the when the activity is first created. onStart() is called when the activity is becoming visible to the user.

Why is onResume called after onCreate?

onResume() will always be called when the activity goes into foreground, but it will never be executed before onCreate() .


2 Answers

  • onCreate: Activity launched for the first time. Here is where you may initialize your stuff.
  • onResume: User returns to the activity after another activity comes into foreground. (onPause)
  • onRestart: User navigates to the activity after it's no longer visible (onStop).

You can see the complete lifecycle on Activity documentation. Your activity stuff would only be lost when onDestroy is called, which happens when you finish it, or when it's destroyed by the system (i.e. when apps with higher priority need memory)

like image 78
ssantos Avatar answered Oct 19 '22 11:10

ssantos


Suppose a dialogue is initiated from your current activity the main window(Activity) will goes to the onPause State. Once you force activity to be in background(Suppose you press home button) The Activity will goes to onPause State.

like image 44
flexdroid Avatar answered Oct 19 '22 11:10

flexdroid