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

What is the life cycle of an Android activity? Why are so many similar sounding methods (onCreate(), onStart(), onResume()) called during initialization, and so many others (onPause(), onStop(), onDestroy()) called at the end?
When are these methods called, and how should they be used properly?

See it in Activity Lifecycle (at Android Developers).
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");
}
}

Activity has six states
Created
Started
Resumed
Paused
Stopped
Destroyed
Activity lifecycle has seven methods
onCreate()
onStart()
onResume()
onPause()
onStop()
onRestart()
onDestroy()
diagram source
Situations
When open the app
onCreate() --> onStart() --> onResume()
When back button pressed and exit the app
onPaused() -- > onStop() --> onDestory()
When home button pressed
onPaused() --> onStop()
After pressed home button when again open app from recent task list or clicked on icon
onRestart() --> onStart() --> onResume()
When open app another app from notification bar or open settings
onPaused() --> onStop()
Back button pressed from another app or settings then used can see our app
onRestart() --> onStart() --> onResume()
When any dialog open on screen
onPause()
After dismiss the dialog or back button from dialog
onResume()
Any phone is ringing and user in the app
onPause() --> onResume()
When user pressed phone's answer button
onPause()
After call end
onResume()
When phone screen off
onPaused() --> onStop()
When screen is turned back on
onRestart() --> onStart() --> onResume()

The entire confusion is caused since Google chose non-intuivitive names instead of something as follows:
onCreateAndPrepareToDisplay() [instead of onCreate() ]
onPrepareToDisplay() [instead of onRestart() ]
onVisible() [instead of onStart() ]
onBeginInteraction() [instead of onResume() ]
onPauseInteraction() [instead of onPause() ]
onInvisible() [instead of onStop]
onDestroy() [no change]
The Activity Diagram can be interpreted as:

ANDROID LIFE-CYCLE
There are seven methods that manage the life cycle of an Android application:
onCreate()
onStart()
onResume()
onRestart()
onPause()
onStop()
onDestroy()
Answer for what are all these methods for:
Let us take a simple scenario where knowing in what order these methods are called will help us give a clarity why they are used.
Suppose you are using a calculator app. Three methods are called in
succession to start the app.
onCreate() - - - > onStart() - - - > onResume()
When I am using the calculator app, suddenly a call comes the.
The calculator activity goes to the background and another activity say.
Dealing with the call comes to the foreground, and now two methods are
called in succession.
onPause() - - - > onStop()
Now say I finish the conversation on the phone, the calculator
activity comes to foreground from the background, so three methods
are called in succession.
onRestart() - - - > onStart() - - - > onResume()
Finally, say I have finished all the tasks in calculator app, and I
want to exit the app. Futher two methods are called in succession.
onStop() - - - > onDestroy()
There are four states an activity can possibly exist:
Starting State
Running State
Paused State
Stopped state
Starting state involves:
Creating a new Linux process, allocating new memory for the new UI objects, and setting up the whole screen. So most of the work is involved here.
Running state involves:
It is the activity (state) that is currently on the screen. This state alone handles things such as typing on the screen, and touching & clicking buttons.
Paused state involves:
When an activity is not in the foreground and instead it is in the background, then the activity is said to be in paused state.
Stopped state involves:
A stopped activity can only be bought into foreground by restarting it and also it can be destroyed at any point in time.
The activity manager handles all these states in such a way that the user experience and performance is always at its best even in scenarios where the new activity is added to the existing activities

I like this question and the answers to it, but so far there isn't coverage of less frequently used callbacks like onPostCreate() or onPostResume(). Steve Pomeroy has attempted a diagram including these and how they relate to Android's Fragment life cycle, at https://github.com/xxv/android-lifecycle. I revised Steve's large diagram to include only the Activity portion and formatted it for letter size one-page printout. I've posted it as a text PDF at https://github.com/code-read/android-lifecycle/blob/master/AndroidActivityLifecycle1.pdf and below is its image:

From the Android Developers page,
onPause():
Called when the system is about to start resuming a previous activity.
This is typically used to commit unsaved changes to persistent data,
stop animations and other things that may be consuming CPU, etc.
Implementations of this method must be very quick because the next
activity will not be resumed until this method returns. Followed by
either onResume() if the activity returns back to the front, or
onStop() if it becomes invisible to the user.
onStop():
Called when the activity is no longer visible to the user, because
another activity has been resumed and is covering this one. This may
happen either because a new activity is being started, an existing one
is being brought in front of this one, or this one is being destroyed.
Followed by either onRestart() if this activity is coming back to
interact with the user, or onDestroy() if this activity is going away.
Now suppose there are three Activities and you go from A to B, then onPause of A will be called now from B to C, then onPause of B and onStop of A will be called.
The paused Activity gets a Resume and Stopped gets Restarted.
When you call this.finish(), onPause-onStop-onDestroy will be called. The main thing to remember is: paused Activities get Stopped and a Stopped activity gets Destroyed whenever Android requires memory for other operations.
I hope it's clear enough.

What is the life cycle of an Android activity?
In android sdk framework, Every android Activity(Window) having lifecycle methods. That means, when user enter into an application, he can see the Activity thats been created in onCreate() lifecycle method. Layouts attached in the window in onCreate() method only.
Activity(Window) has following lifecycle states:
Create - Activity is created.
Start - Current activity gets started.
Resume - Current activity has been in resumed state.
Restart - Current activity has been in restarted.
Pause - Current activity has been in Paused state.
Stop - Current activity has been in stopped state.
destroy - Current activity has been in destroyed state.
Why are so many similar sounding methods (onCreate(), onStart(),
onResume()) called during initialization, and so many others
(onPause(), onStop(), onDestroy()) called at the end?
First time user enter into an application:
When opening the application, we can see one Window(Activity). onCreate (created) -> onStart(started) -> onResume(resume state) will be called.
Close the application from background:
when closing the application from the background, activity has to be destroyed to free up some memory. So, onPause -> onStop -> onDestroy methods will be called.
When are these methods called, and how should they be used properly?
Starts the Application:
When user enter into an activity or application for the first time:
onCreate()
onStart()
onResume()
When you run the app from android studio:
onCreate()
onStart()
onResume()
Activity Transition:
When moving from First Activity -> Second Activity:
first_activity : onPause()
second_activity : onCreate()
second_activity : onStart()
second_activity : onResume()
first_activity : onStop()
When moving from Second Activity -> First Activity:
second_activity : onPause()
first_activity : onRestart()
first_activity : onStart()
first_activity : onResume()
second_activity : onStop()
second_activity : onDestroy()
Overview Button:
When user clicks on Overview Button (hardware third button - recent list):
onPause()
onStop()
After user Dismiss the Overview Button (or) User went to some other apps from the recent list and coming back to the Application:
onRestart()
onStart()
onResume()
Home Button:
When user clicks on Home Button:
onPause()
onStop()
User search the home screen and clicks on application icon to coming back to the activity:
onRestart()
onStart()
onResume()
User gets Phone Call:
When user in an Activity, phone call came up:
onPause()
onStop()
If User doesn't attend the call, it disconnect automatically and back to activity (missed call):
onRestart()
onStart()
onResume()
If User doesn't attends the call:
N/A - No lifecycle will be called.
Power off Button:
When User power off the button:
onPause()
onStop()
When unlocks the device:
onRestart()
onStart()
onResume()
Pop Up Dialog:
When pop up dialog came up - No lifecycle will be called
Restart Device or Switch off:
When user restarts or switch off device:
onPause()
onStop()
When user clicks on app icon from the home screen:
onCreate()
onStart()
onResume()

Adding some more info on top of highly rated answer (Added additional section of KILLABLE and next set of methods, which are going to be called in the life cycle):
Source: developer.android.com
Note the "Killable" column in the above table -- for those methods that are marked as being killable, after that method returns the process hosting the activity may be killed by the system at any time without another line of its code being executed.
Because of this, you should use the onPause() method to write any persistent data (such as user edits) to storage. In addition, the method onSaveInstanceState(Bundle) is called before placing the activity in such a background state, allowing you to save away any dynamic instance state in your activity into the given Bundle, to be later received in onCreate(Bundle) if the activity needs to be re-created.
Note that it is important to save persistent data in onPause() instead of onSaveInstanceState(Bundle) because the latter is not part of the lifecycle callbacks, so will not be called in every situation as described in its documentation.
I would like to add few more methods. These are not listed as life cycle methods but they will be called during life cycle depending on some conditions. Depending on your requirement, you may have to implement these methods in your application for proper handling of state.
onPostCreate(Bundle savedInstanceState)
Called when activity start-up is complete (after onStart() and onRestoreInstanceState(Bundle) have been called).
onPostResume()
Called when activity resume is complete (after onResume() has been called).
onSaveInstanceState(Bundle outState)
Called to retrieve per-instance state from an activity before being killed so that the state can be restored in onCreate(Bundle) or onRestoreInstanceState(Bundle) (the Bundle populated by this method will be passed to both).
onRestoreInstanceState(Bundle savedInstanceState)
This method is called after onStart() when the activity is being re-initialized from a previously saved state, given here in savedInstanceState.
My application code using all these methods:
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private EditText txtUserName;
private EditText txtPassword;
Button loginButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("Ravi","Main OnCreate");
txtUserName=(EditText) findViewById(R.id.username);
txtPassword=(EditText) findViewById(R.id.password);
loginButton = (Button) findViewById(R.id.login);
loginButton.setOnClickListener(this);
}
#Override
public void onClick(View view) {
Log.d("Ravi", "Login processing initiated");
Intent intent = new Intent(this,LoginActivity.class);
Bundle bundle = new Bundle();
bundle.putString("userName",txtUserName.getText().toString());
bundle.putString("password",txtPassword.getText().toString());
intent.putExtras(bundle);
startActivityForResult(intent,1);
// IntentFilter
}
public void onActivityResult(int requestCode, int resultCode, Intent resIntent){
Log.d("Ravi back result:", "start");
String result = resIntent.getStringExtra("result");
Log.d("Ravi back result:", result);
TextView txtView = (TextView)findViewById(R.id.txtView);
txtView.setText(result);
Intent sendIntent = new Intent();
//sendIntent.setPackage("com.whatsapp");
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "Message...");
sendIntent.setType("text/plain");
startActivity(sendIntent);
}
#Override
protected void onStart() {
super.onStart();
Log.d("Ravi","Main Start");
}
#Override
protected void onRestart() {
super.onRestart();
Log.d("Ravi","Main ReStart");
}
#Override
protected void onPause() {
super.onPause();
Log.d("Ravi","Main Pause");
}
#Override
protected void onResume() {
super.onResume();
Log.d("Ravi","Main Resume");
}
#Override
protected void onStop() {
super.onStop();
Log.d("Ravi","Main Stop");
}
#Override
protected void onDestroy() {
super.onDestroy();
Log.d("Ravi","Main OnDestroy");
}
#Override
public void onPostCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onPostCreate(savedInstanceState, persistentState);
Log.d("Ravi","Main onPostCreate");
}
#Override
protected void onPostResume() {
super.onPostResume();
Log.d("Ravi","Main PostResume");
}
#Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
super.onSaveInstanceState(outState, outPersistentState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
}
}
Login Activity:
public class LoginActivity extends AppCompatActivity {
private TextView txtView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
txtView = (TextView) findViewById(R.id.Result);
Log.d("Ravi","Login OnCreate");
Bundle bundle = getIntent().getExtras();
txtView.setText(bundle.getString("userName")+":"+bundle.getString("password"));
//Intent intent = new Intent(this,MainActivity.class);
Intent intent = new Intent();
intent.putExtra("result","Success");
setResult(1,intent);
// finish();
}
}
output: ( Before pause)
D/Ravi: Main OnCreate
D/Ravi: Main Start
D/Ravi: Main Resume
D/Ravi: Main PostResume
output: ( After resume from pause)
D/Ravi: Main ReStart
D/Ravi: Main Start
D/Ravi: Main Resume
D/Ravi: Main PostResume
Note that onPostResume() is invoked even though it's not quoted as life cycle method.

I run some logs as per answers above and here is the output:
Starting Activity
On Activity Load (First Time)
————————————————————————————————————————————————
D/IndividualChatActivity: onCreate:
D/IndividualChatActivity: onStart:
D/IndividualChatActivity: onResume:
D/IndividualChatActivity: onPostResume:
Reload After BackPressed
————————————————————————————————————————————————
D/IndividualChatActivity: onCreate:
D/IndividualChatActivity: onStart:
D/IndividualChatActivity: onResume:
D/IndividualChatActivity: onPostResume:
OnMaximize(Circle Button)
————————————————————————————————————————————————
D/IndividualChatActivity: onRestart:
D/IndividualChatActivity: onStart:
D/IndividualChatActivity: onResume:
D/IndividualChatActivity: onPostResume:
OnMaximize(Square Button)
————————————————————————————————————————————————
D/IndividualChatActivity: onRestart:
D/IndividualChatActivity: onStart:
D/IndividualChatActivity: onResume:
D/IndividualChatActivity: onPostResume:
Stopping The Activity
On BackPressed
————————————————————————————————————————————————
D/IndividualChatActivity: onPause:
D/IndividualChatActivity: onStop:
D/IndividualChatActivity: onDestroy:
OnMinimize (Circle Button)
————————————————————————————————————————————————
D/IndividualChatActivity: onPause:
D/IndividualChatActivity: onStop:
OnMinimize (Square Button)
————————————————————————————————————————————————
D/IndividualChatActivity: onPause:
D/IndividualChatActivity: onStop:
Going To Another Activity
————————————————————————————————————————————————
D/IndividualChatActivity: onPause:
D/IndividualChatActivity: onStop:
Close The App
————————————————————————————————————————————————
D/IndividualChatActivity: onDestroy:
In my personal opinion only two are required onStart and onStop.
onResume seems to be in every instance of getting back, and onPause in every instance of leaving (except for closing the app).

Related

Running code in onPause() or onStop() state of the activity

There is a function in my android app that needs to run every time the user tries to edit his or her profile. There are two parts of edit profile in my app (please don't ask why, it has a very long tedious reason behind it). I need to revert back the changes the user did in the first part of the edit profile if the user decides to cancel everything. I have made a cancel button in the part two of edit profile but my question is, what if user presses the return button or the home button on the device and the app calls the onPause() and on onStop()? how can I run the same code in these two phases of the activities? Anyone out there who knows how to put code in different states on activities? Do I just make a function onPause() and stick the code in there? Would that work?
Yes, it should definitely work. In your case, you should write your code in onPause() method.
Here is a summary of the Activity Lifecycle:
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().
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Write your code here
}
onStart():
Called when the activity is becoming visible to the user.
Followed by onResume() if the activity comes to the foreground, or onStop() if it becomes hidden.
#Override
public void onStart() {
super.onStart();
//Write your code here
}
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().
#Override
public void onResume() {
super.onResume();
//Write your code here
}
onPause():
Called when the system is about to start resuming a previous activity. This is typically used to commit unsaved changes to persistent data, stop animations and other things that may be consuming CPU, etc. Implementations of this method must be very quick because the next activity will not be resumed until this method returns.
Followed by either onResume() if the activity returns back to the front, or onStop() if it becomes invisible to the user.
#Override
public void onPause() {
super.onPause();
//Write your code here
}
onStop():
Called when the activity is no longer visible to the user, because another activity has been resumed and is covering this one. This may happen either because a new activity is being started, an existing one is being brought in front of this one, or this one is being destroyed.
Followed by either onRestart() if this activity is coming back to interact with the user, or onDestroy() if this activity is going away.
#Override
public void onStop() {
super.onStop();
//Write your code here
}
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.
#Override
public void onDestroy() {
super.onDestroy();
//Write your code here
}
You can do many things inside both onPause and onStop, just remember to call super.onPause();, super.onStop(); or whatever you need inside each one, just follow the pattern below. Simply add the code to your Activity and you're good to go.
#Override
public void onPause() {
super.onPause(); // Always call the superclass method first
// Do what you want.
}
Additionaly, if you want your users to be able to go back on your activity and edit something instead of closing it, you can just call onBackPressed():
#Override
public void onBackPressed() {
super.onBackPressed();
// You can just call onStop to close the app
// or do what you want.
}
Only onPause is guaranteed to be called

What is the difference between an activity going in the background and an activity becoming invisible?

I am new to android.I have learned that the onPause() method is called when some other activity comes in the foreground and onStop() method is called when an activity is no longer visible.Can someone please explain what's the difference between going in background and becoming invisible giving some practical example.
Best example? A popup, your activity is still visible, so only onPause() is called. Becoming invisible is when another activity is launched, the app is sent to the background, the user switches to another app et.
Think about two cases
1. Calling Activity B as dialog
In this case, some part of Activty A will be visible. So only onPause() method will get called for Activity A. And when you will be back from Activity B to A, onResume() of Activity A will get called.
2.Calling Activity B as normal activity
In this case, Activity A will be completely invisible, So onPause() and onStop() both will be called. And when you will be back from Activity B to A, onRestart(), onStart() and onResume() methods of Activity A will be called.
Have a look
Case 1: If you call normal activity. (Which is going to hide caller activity)
onPause()
onStop()
<------- Back to caller
onRestart()
onStart()
onResume()
Case 2: If you call activity-as-dialog. (Which is going to partially hide caller activity)
onPause()
<------- Back to caller
onResume()
whenever a dialog box appears on any activity then activity's onPause() called and this activity holds the first position in stack(Top), on the other hand whenever we switches activity from one to another the previous activity's on Stop() method called and its automatically garbage collected in sometimes.

onDestroy() gets called when the back button is pressed

In my Activity, I have overrode onDestory() and just put a log call to show if this method is being called. (tested on Android 4.2.2 and 4.4.4)
#Override
protected void onDestroy() {
Log.i(TAG, "onDestroy() was called");
super.onDestroy();
}
When I press the back button, this method gets called (I saw the log).
I believe this should not happen unless phone gets low in memory or something. I have nothing much in the app but the MainActivity and some fragments.
Here is the log when the user is in the MainActivity and presses the back button:
I/MainActivity? onBackPressed() was called
I/MainActivity? onStop() was called
I/MainActivity? onDestroy() was called
Why this happens?
I also checked for isFinishing() in the onPause() and it always returns true
From the Javadoc :
Perform any final cleanup before an 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. Note: do not count on this
method being called as a place for saving data!
When you press back button inside an Activity, it will call finish(), which will "close" it.
Activity.java
/**
* Called when the activity has detected the user's press of the back
* key. The default implementation simply finishes the current activity,
* but you can override this to do whatever you want.
*/
public void onBackPressed() {
if (!mFragments.popBackStackImmediate()) {
finish();
}
}
When it happens, onDestroy() can (and usually will) be called.
protected void onDestroy ()
Perform any final cleanup before an 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.
The same reason also goes to why putting isFinishing() inside onPause() always returns true, if you press the back button (call finish()). It will not return true if you hide the Activity with other method, e.g. pressing the home button.

Calling a method in android during onload event

onCreate() does not get called when I leave the application using back button and start it immediately. I believe this is because, Android has not killed the application process yet. I tried using #AfterViews, the same happens. How could I make sure that every time the application is started, my specific code runs?
Does not get called when I leave the application using back button and then start.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
methodToRun();
}
I use this onBackPressed() to exit the application.
#Override
public void onBackPressed() {
this.moveTaskToBack(true);
this.finish();
}
Even #AfterViews does not get called when I leave the application using back button and then start.
#AfterViews
void checkAgreementFlag(){
methodToRun();
}
I want methodToRun() to always get called. How would I do it?
Call methodToRun() from onResume() of activity.
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.
onCreate(): is called when your application is starting first time.
onRestart(): Called after your activity has been stopped, prior to it being started again.
onStart(): Called when the activity is becoming visible to the user.
onStop() : When the activity is no longer visible.
For the back key scenario activity lifecycle:
onCreate()->onStart()->onResume()->Activity running
After pressing back key
onPause()->onStop()
If the activity is coming back then
onRestart()->onStart()->onResume()->Activity running
otherwise onDestroy() will be called.

basics of android activity life cycle functions

I was testing out this code which shows which state an activity is in
public class Activity101Activity extends Activity {
String tag = "Lifecycle";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.main);
setContentView(R.layout.activity_activity101);
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");
}
}
so I see that onDestroy() is only called when we press the back button while the activity is on screen, and is never called otherwise. So it should be running in the back ground if I press the home button while the activity is running. However, if I go to Settings -> Apps -> Running I can't see it on the list. So does that mean it is running in the background or not?
Again, Again, this code shows that onPause() is always followed by onStop() and onStart() is always followed by onResume(). So why are they defined as different functions in the Android environment and not combined?
Here I give you biref idea of activity life cycle...
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, or onStop() if it becomes hidden.
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.
So..onStart method call when activity comes in the foreground without interaction of user...and onResume method call when user starts interaction...so the functions of all methods is different ..
And once you press home button or back button your app running in the background and once you kill it from task manager it will shows nothing in the settings...
Once the activity goes in backstack, it is in suspended mode. So you dont see it in running app list. Once you relaunch such suspended application, it comes to foreground from backstack and starts to run. It is kept in backstack to preserve its state and resume from the place where it got stopped before going in background.
To understand why, onStart is needed before onResume follow the link below. It will clear all your doubts very clearly:
Difference between onStart() and onResume()
onStart isn't always followed by onResume. onStart is called when you Activity is visible, and onResume is called when your Activity is active. For example, an Activity could be visible but not active if there was a dialog partially covering it.
Thats' because there's a chance that onStart might not get called even when onResume actually is, there's a scenario when the activity might go to onPause only, without going to onStop [it only happens when activity is partially visible, not completelly covered by another activity], hence when comming back to activity only onResume will be called and not onStart.
Same with onPause, its always executed before onStop but onStop might not be called after onPause, as mentioned before, it could be called without onStop being actually called. If you press HOME you will not see the behavior i just explained because the activity is not partially visible, in order to reproduce it you have to find a way to make another component come on top without completely covering the activity...
Hope this helps.
Regards!

Categories

Resources