Android Activity Life Cycle - What Are All These Methods For

Android activity life cycle - what are all these methods for?

See it in Activity Lifecycle (at Android Developers).

Sample Image

onCreate():

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

onRestart():

Called after your activity has been stopped, prior to it being started
again. Always followed by onStart()

onStart():

Called when the activity is becoming visible to the user. Followed by
onResume() if the activity comes to the foreground.

onResume():

Called when the activity will start interacting with the user. At this
point your activity is at the top of the activity stack, with user
input going to it. Always followed by onPause().

onPause ():

Called as part of the activity lifecycle when an activity is going
into the background,
but has not (yet) been killed. The counterpart to onResume().
When activity B is launched in front of activity A, this callback will be invoked on A.
B will not be created until A's onPause() returns, so be sure to not
do anything lengthy here.

onStop():

Called when you are no longer visible to the user. You will next
receive either onRestart(), onDestroy(), or nothing, depending on
later user activity.
Note that this method may never be called, in low memory situations
where the system does not have enough memory to keep your activity's
process running after its onPause() method is called.

onDestroy():

The final call you receive before your activity is destroyed. This
can happen either because the activity is finishing (someone called
finish() on it, or because the system is temporarily destroying this
instance of the activity to save space. You can distinguish between> these two scenarios with the isFinishing() method.

When the Activity first time loads the events are called as below:

onCreate()
onStart()
onResume()

When you click on Phone button the Activity goes to the background and the below events are called:

onPause()
onStop()

Exit the phone dialer and the below events will be called:

onRestart()
onStart()
onResume()

When you click the back button OR try to finish() the activity the events are called as below:

onPause()
onStop()
onDestroy()

Activity States

The Android OS uses a priority queue to assist in managing activities running on the device. Based on the state a particular Android activity is in, it will be assigned a certain priority within the OS. This priority system helps Android identify activities that are no longer in use, allowing the OS to reclaim memory and resources. The following diagram illustrates the states an activity can go through, during its lifetime:

These states can be broken into three main groups as follows:

Active or Running - Activities are considered active or running if they are in the foreground, also known as the top of the activity stack. This is considered the highest priority activity in the Android Activity stack, and as such will only be killed by the OS in extreme situations, such as if the activity tries to use more memory than is available on the device as this could cause the UI to become unresponsive.

Paused - When the device goes to sleep, or an activity is still visible but partially hidden by a new, non-full-sized or transparent activity, the activity is considered paused. Paused activities are still alive, that is, they maintain all state and member information, and remain attached to the window manager. This is considered to be the second highest priority activity in the Android Activity stack and, as such, will only be killed by the OS if killing this activity will satisfy the resource requirements needed to keep the Active/Running Activity stable and responsive.

Stopped - Activities that are completely obscured by another activity are considered stopped or in the background. Stopped activities still try to retain their state and member information for as long as possible, but stopped activities are considered to be the lowest priority of the three states and, as such, the OS will kill activities in this state first to satisfy the resource requirements of higher priority activities.

*Sample activity to understand the life cycle**

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends Activity {
String tag = "LifeCycleEvents";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.d(tag, "In the onCreate() event");
}
public void onStart()
{
super.onStart();
Log.d(tag, "In the onStart() event");
}
public void onRestart()
{
super.onRestart();
Log.d(tag, "In the onRestart() event");
}
public void onResume()
{
super.onResume();
Log.d(tag, "In the onResume() event");
}
public void onPause()
{
super.onPause();
Log.d(tag, "In the onPause() event");
}
public void onStop()
{
super.onStop();
Log.d(tag, "In the onStop() event");
}
public void onDestroy()
{
super.onDestroy();
Log.d(tag, "In the onDestroy() event");
}
}

Android activity and fragment life cycle - do I need to use all methods in my code?

Nope. You can override those methods to add more functionality to your app but those methods already have their own function and will run whether you override it or not.

You could read more on the Android Activity Life Cycle: http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle

You could see this post as well: Android activity life cycle - what are all these methods for?

What are the Android application lifecycle methods? (not activity life cycle methods.)

This happens because of the Activity LifeCycle. When you close your app by pressing the home button, the onStop() method of the respective Activity which was active at the time is called upon. This method does not destroy the Activity completely, it only stops it.

The Activities in the Android OS are destroyed by calling onDestroy() method of the respective Activity. However, onDestroy() method cannot be called directly because it is a method of Activity's LifeCycle. It gets called automatically by the Android OS. To ensure that Activity's onDestroy() method gets called as soon as your Activity stops, we will call finish() method inside the onStop() method of your respective Activity(s).

@Override
protected void onStop() {
super.onStop();
finish();
}

Now, when you'll start your app again, it will start from the beginning i.e. the splash screen.

When to use which method of Activity Life Cycle

You can refer this.

onCreate: This method is called only once. Use it for initialization of all your views such as TextView, Layouts, etc.

onResume: It will be called every time your application will come to foreground from background. So if you have any broadcast receiver, which you want to be working only when your application is in foreground, you can probably register it here.

onPause: It will be called just before your application moves to background (may be when you receive any call or click any notification of other app in notification bar.) So if you want to do some task when your app is moving in background, this is the place you can do it. Again the best example would be of unregistered any broadcast receiver. (Broadcast receiver is just one example. Not the only use of onResume and onPause)

onDestroy: It will be called before your app is going to exit. So if you want to do something before app exit, you can do here. May be send a error report in case of crash. Or stop a service which was being executed.

Hope this gives a hint.

Which android lifecycle methods are guaranteed to be called after a call to finish()?

Activity A onPause(), and onStop() is guarantee to be called when you call to finish(). But onDestroy() is not guarantee to be called when activity A restarts activity B. When activity A is restarting onCreate(), onStart(), and onResume() will be called respectively.

But all the lifecycle events is guarantee to be called when you use the activity Lifecycle to observe the Lifecycle.Event of say activity.

You can test it like below to see for yourself:

class ActivityB : AppCompatActivity() {
override fun onResume() {
super.onResume()
startActivity(Intent(this, ActivityA::class.java))
}
}

class ActivityA : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)

Log.d("tag","onCreate")

lifecycle.addObserver(object:LifecycleEventObserver{
override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
Log.d("lifecycleEvent","$event")
}
})
}
override fun onStart() {
super.onStart()
Log.d("tag","onStart")
}

override fun onResume() {
super.onResume()
Log.d("tag","onResume")
}

override fun onPause() {
super.onPause()
Log.d("tag","onPause")
}

override fun onStop() {
super.onStop()
Log.d("tag","onStop")
}
}

What methods are invoked in the Activity Lifecycle in the following cases:

both pressing home button and receiving a call don't remove the activity from the task's stack, and will be available when you re-enter the app => onPause() => onStop().

as the activity lifecycle diagram shows, re-entering the app calls => onRestart() => onStart() => onResume()

pressing the back button instead kills the activity => onPause() => onStop() => onDestroy()

re-entering the app in this case calls the classics => onCreate() => onStart() => onResume()

EDIT

from http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle

If an activity has lost focus but is
still visible (that is, a new
non-full-sized or transparent activity
has focus on top of your activity), it
is paused. A paused activity is
completely alive (it maintains all
state and member information and
remains attached to the window
manager), but can be killed by the
system in extreme low memory
situations.

Understanding the Life cycle of Activity and Service

Now when the user minimizes the app and the service is running and since Android OS is short of memory then it clears the App.

When Android is short on memory, it terminates a process.

Does the Android OS clear the memory of the whole app (Screen A & Screen B) or only my Screen B?

By default, your app uses a single process. So, when Android terminates your process, everything of your app goes away.

Will my service also be cleared or will it continue to run?

By default, your app uses a single process. So, when Android terminates your process, your service will also go away. Some developers elect to put their service in a separate process (via the android:process manifest attribute) to help the service stay around longer, but that makes your app a bit more difficult to build.

If it is cleared then can a foreground service with a notification help me to overcome this?

A foreground service makes it far less likely that Android will terminate that service's process to free up system RAM. However, you should only have a service running when it is actively delivering value to the user.

Callback methods - Why are life cycle methods called as callback methods?

The term callback describes the mechanism used by android to handle events.These methods are declared by the app and then the app goes about with other things. At the appropriate moment, that is when the event happens the android system calls back into the app's code and executes it.

Activity Life Cycle

Check out the Documentation for Activity All of these are in there, and many of them contain more detail than what I've listed here.

  1. This hook is called whenever the content view of the screen changes (due to a call to Window.setContentView or Window.addContentView).
  2. Called when activity start-up is complete (after onStart() and onRestoreInstanceState(Bundle) have been called).
  3. Called when activity resume is complete (after onResume() has been called).
  4. This hook is called whenever the window focus changes.
  5. Called as part of the activity lifecycle when an activity is about to go into the background as the result of user choice. For example, when the user presses the Home key, onUserLeaveHint() will be called, but when an incoming phone call causes the in-call Activity to be automatically brought to the foreground, onUserLeaveHint() will not be called on the activity being interrupted. In cases when it is invoked, this method is called right before the activity's onPause() callback.
    This callback and onUserInteraction() are intended to help activities manage status bar notifications intelligently; specifically, for helping activities determine the proper time to cancel a notfication.
  6. Called whenever a key, touch, or trackball event is dispatched to the activity.
  7. Called when the window has been detached from the window manager.


Related Topics



Leave a reply



Submit