What is an Activity?
An activity represents a single screen with a user interface just like window or frame of Java. Android activity is the subclass of ContextThemeWrapper class. If you have worked with C, C++ or Java programming language then you must have seen that your program starts from main() function.
Android Activity Lifecycle methods
OnCreate-Create the Activity(Constructor)
OnStart-When user can see the screen
OnResume-When user can interact with the screen
OnPause-When App is partially visible.
OnStop-When app is not visible to user
On Destroy- When activity is destroy(app is killed)
OnRestart-When we navigate back to activate minimize and back to app
Some use cases For Better understanding-
1.Transition of activity- Flow of activity life cycle is on intent o one activity to other
OnCreate(1)-OnStart(1)-OnResume(1)-OnPause(1)-OnCreate(2)-OnResume(2)-OnStop(1)
2.Back Button- flow of activity life cycle is
OnPause-Onrestart-OnStart-OnResume-OnStop-OnDestory
3.OFFLock Button- State changes to
Onpause-OnStop
4.ON Lock Button- State changes to
OnRestart-OnStart-OnResume
5.Home Button-State changes to
OnPause-OnStop
6.Kill App
OnPause-Onstop-OnDestroy
7.Ask user permission like access to contact, location, etc. Should be written in onStart.
8.Navigate Back
OnRestart-OnStart
9.Login Status-Eg.Bank Case logout on minimize
OnStart-OnStop
10.Pause video on youtube-
OnPause-Video Pause
OnResume-Video Resume
11.Weather app
Refresh data each time activity is open- write function in Onstart
The above points cover the entire story but just for keeping it our coding style
package com.example.helloworld;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
public class MainActivity extends Activity {
String msg = "Android : ";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(msg, "The onCreate() event");
}
/** Called when the activity is about to become visible. */
@Override
protected void onStart() {
super.onStart();
Log.d(msg, "The onStart() event");
}
/** Called when the activity has become visible. */
@Override
protected void onResume() {
super.onResume();
Log.d(msg, "The onResume() event");
}
/** Called when another activity is taking focus. */
@Override
protected void onPause() {
super.onPause();
Log.d(msg, "The onPause() event");
}
/** Called when the activity is no longer visible. */
@Override
protected void onStop() {
super.onStop();
Log.d(msg, "The onStop() event");
}
/** Called just before the activity is destroyed. */
@Override
public void onDestroy() {
super.onDestroy();
Log.d(msg, "The onDestroy() event");
}
}
That’s it.Keep coding!!